char array to string specifying an index - c#

I am trying make a clock. The hour is a string. I want to put that hour into a char array so i can separate the hour into one or two indexes. That way i can use a case on the individual indexes to ultimately bind it to a grid and draw a line for the digital time..
So, the hour is converted to an array. But i want to take the first index 0 and store it into a string or int so i can pass it into a function where i can use a case on it. if i leave it as a char and convert it to an int i get a number like 50 which is no good.
So, when i try to assign the first index of the array to a string it wont let me convert from array to string.
hr1 = hours[0];
What is my best option of seperating the hour into separate indexes and then converting it over to the proper int? Also, the time is on 24 hour and i would like it to be 12 hour.
private void _timer_Elapsed(object sender, EventArgs e)
{
DateTime now = DateTime.Now;
//DigitalTime = now.ToString("hh:mm:ss tt");
//DigitalTime = now.ToString();
//DigitalTime = DateTime.Now.Hour.ToString();
SecondAngle = now.Second * 6;
MinuteAngle = now.Minute * 6;
HourAngle = (now.Hour * 30) + (now.Minute * 0.5);
string hrs, hr1, hr2;
char[] hours = new char[15];
hrs = DateTime.Now.Hour.ToString("hh:mm:ss tt");
hours = hrs.ToCharArray();
if (hours.Length > 1)
{
hr1 = hours[0]; // error -
hr2 = hours[1];
// SetHourDigit1(Convert.ToInt32(hr1));
}
else
{
// hr1 = '0';
hr2 = hours[0];
}
}
public void SetHourDigit1(int num)
{
switch (num)
{
case 0:
MessageBox.Show("num" + num);
break;
case 1:
MessageBox.Show("num" + num);
break;
case 2:
break;
}
}

I would avoid messing with strings and char arrays altogether. Use arithmetic instead:
int hour = DateTime.Now.Hour;
int leastSignificantDigit = hour % 10;
int mostSignificantDigit = hour / 10;
// Use one of these as input for your switch statement.
% is the modulo operator; the remainder of a division by 10 in this case.
Edit: I noticed you want to have a 12-hour clock. You can add some additional computation for this. Replacement for the first line of code:
int hour = DateTime.Now.Hour % 12;
if (hour == 0) hour = 12;

if (hours.Length > 1)
{
hr1 = hours[0].ToString(); // no error -
hr2 = hours[1].ToString();
// SetHourDigit1(Convert.ToInt32(hr1));
}
but if you want to get parts of time use this:
dateparts = datestring.splite(':');
string hour = dateparts[0];
string minute = dateparts[1];
string s = dateparts[2];
now you have hour,minute,second and t.
because of you can trust the parts use int.parse to convert them to int.
int nhour = int.parse(hour);
int nminute = int.parse(minute);
int nsecond = int.parse(s);
for 24 hours
hrs = DateTime.Now.Hour.ToString("HH:mm:ss");
This is a usefull link for u:
DateTime.ToString() Pattern

Use the modulo (%) operator to convert the 24 hour value to 12 hours, and also to get the second digit of the two digit number. There is no reason to format it as a string and then convert it back to numbers.
private void _timer_Elapsed(object sender, EventArgs e) {
DateTime now = DateTime.Now;
int hour12 = now.Hour % 12;
SecondAngle = now.Second * 6;
MinuteAngle = now.Minute * 6;
HourAngle = (hour12 * 30) + (now.Minute * 0.5);
SetHourDigit1(hour12 / 10);
SetHourDigit2(hour12 % 10);
}

Related

Divide Into Monthly Installments

Hi I'm trying to make Monthly Installments of a "double value"
The Problem is that the decimal values get divided too, and i don't need that happen.
Example :
List<Installments> InstallmentList {get; set;}
for (int i = 0 ; int i <= Month ; i++)
{
double Value = 90.10 ;
int Month = 3;
InstallmentCost = Value / Month;
InstallmentList.Add (new Installment {InstallmentCost = example.InstallmentCost} )
}
Doing That i will get a list of Installments where the value will be :
Installment = 30.03333333333333;
Installment = 30.03333333333333;
Installment = 30.03333333333333;
But I need that the decimals do not divide and and only the last Installment gets it
Example Of The Results that i need :
Installment = 30.00;
Installment = 30.00;
Installment = 30.10;
Just truncate the installment which only takes the integral part (if not C# then convert to something like int and back to double would do the trick!).
I have used C#, here's the working solution:-
double Value = 90.10;
int Month = 3;
for (int i = 1; i <= Month ; i++)
{
var installmentCost = Math.Truncate(Value / Month);
InstallmentList.Add(new Installment {InstallmentCost = installmentCost});
}
// Extract pending balance to be adjusted, total - the sum of all installments
double pendingBalanceToAdjust = Value - InstallmentList.Sum((s) => s.InstallmentCost);
// Update to the last installment
if (pendingBalanceToAdjust > 0)
InstallmentList.Last().InstallmentCost += pendingBalanceToAdjust;
You can calculate the remainder at the start and then divide the rest into equal parts:
double value = 90.10;
int month = 3;
// calculate the remainder with precision 0.1
double remainder = value % (month * 0.1);
double installmentValue = (value - remainder) / month;
for (int i = 0; i < month - 1; i++)
InstallmentList.Add(new Installment {InstallmentCost = installmentCost});
InstallmentList.Add(new Installment {InstallmentCost = installmentCost + remainder});
the expression value % (month * 0.1) effectively works out what is left over if you keep giving each of the 3 months 0.1 from the value until you can no longer carry on.
Changing the precision to 0.01 will change the outcome to: 30.03, 30.03, 30.04
Linq approach
decimal value = 90.10m;
int month = 3;
List<Installment> installments = Enumerable.Range(0, month).Select(x => new Installment() { InstallmentCost = Math.Floor(value / month) }).ToList();
installments.Last().InstallmentCost += (value - installments.Sum(x => x.InstallmentCost));

How to swap a 2 digit number and find the larger of the result?

I want to use the number 25 then swap the two digits (the 2 and the 5) and then compare the swapped number (52) to the first number (25). If the swapped number is bigger I get a true and if the swapped number is smaller than the first number I get a false.
Example of what I want:
Input:
25
Output:
True //Because 25 reversed is 52, so it´s bigger
This is what I've tried:
int firstdigit = num / 10;
int secondigit = num % 10;
string res = secondigit + firstdigit.ToString();
if(res > num)
{
return true;
}
return false;
The problem now is that the "if" is not working anymore because res is a string and num is an int, but when I make res an int then I cant add the first digit and second digit because it's obviously different if I do 5 + 2 with ints (7) or 5 + 2 with strings (52).
You need to construct the reversed int value and compare against that:
int firstdigit = num / 10;
int secondigit = num % 10;
int reversed = firstdigit + seconddigit * 10;
if (reversed > num)
...
If you look at the code above, you should see that it's just reversing the logic that you used to extract the first and second digits.
Nice solution.
Maybe that's enough for you
int firstdigit = num / 10;
int secondigit = num % 10;
if(secondigit > firstdigit)
{
return true;
}
return false;

How to check if a number is between two numbers and use in conditional

Basically, this is what I want to do.. I have two integers, start and end of a range and I want to check if given string contains a number between these two integers. The string can also contain the integer themselves and should be included.
int availableRangeBegin = 12;
int availableRangeEnd = 20;
String prefDay = "15"
if (int.Parse(prefday) is any number between range 12 and 20 including 12 and 20 )
{
// do something
// will get here in this case because 12 < 15 < 20
}
I'm not sure how I can check for a number in a range. Any help will be appreciated!
int availableRangeBegin = 12;
int availableRangeEnd = 20;
string prefDay = "20";
int number = int.Parse(prefDay);
if (number >= availableRangeBegin && number <= availableRangeEnd)
{
}
Starting with C#9.0 we can write
x is >= 1 and <= 100 // Note that we must write x only once.
// "is" introduces a pattern matching expression.
// "and" is part of the pattern matching unlike the logical "&&".
// With "&&" we would have to write: x is >= 1 && x is <= 100
or in your case
int availableRangeBegin = 12;
int availableRangeEnd = 20;
string prefDay = "20";
int number = int.Parse(prefDay);
if (number is >= availableRangeBegin and <= availableRangeEnd)
{
}
Which is closer to what you originally asked

splitting a 6 digit integer in C#

I have an 6digit integer, let's say "153060" that I'll like to split into
int a = 15 (first 2 digits),
int b = 30 (second 2 digits),
int c = 60 (third 2 digits),
The first thing that comes to mind is to convert the int to a string, split it using SubString (or a variation), and then convert back to an int.
This seems like a highly inefficient way to do it though. Can anyone recommend a better/faster way to tackle this?
Thanks!
Additional Info: the reason for splitting the int is because the 6-digit integer represents HHMMSS, and I'd like to use it to create a new DateTime instance:
DateTime myDateTime = new DateTime (Year, Month, Day, a , b, c);
However, the user-field can only accept integers.
int y = number / 10000;
int m = (number - y*10000) / 100;
in d = number % 100;
If your end goal is a DateTime, you could use TimeSpan.ParseExact to extract a TimeSpan from the string, then add it to a DateTime:
TimeSpan time = TimeSpan.ParseExact(time, "hhmmss", CultureInfo.InvariantCulture);
DateTime myDateTime = new DateTime(2011, 11, 2);
myDateTime = myDateTime.Add(time);
(Assumes >= .NET 4)
How about something like this?
int i = 153060;
int a = i / 10000;
int b = (i - (a * 10000)) / 100;
int c = (i - ((a * 10000) + (b * 100)));
You can do that without converting to string with:
int a = 153060 / 10000;
int b = (153060 / 100) % 100;
int c = 153060 % 100;
I am not sure about how efficient that is compared to converting to string. I think this is only 4 operations. So it might be faster.

spliting 6 digit int into 3 parts?

I want to get a six digit number by user and spit it into 3 parts as(day, month, year)
Example:
int date=111213;
day =11;
month =12;
year =13;
I think I have to convert it into string then by using substring() I can do this.
Any easy Idea ??
How about:
// Assuming a more sensible format, where the logically most significant part
// is the most significant part of the number too. That would allow sorting by
// integer value to be equivalent to sorting chronologically.
int day = date % 100;
int month = (date / 100) % 100;
int year = date / 10000;
// Assuming the format from the question (not sensible IMO)
int year = date % 100;
int month = (date / 100) % 100;
int day = date / 10000;
(Do you have to store your data like this to start with? Ick.)
Storing a date as an integer like this isn't ideal, but if you must do it -- and you're sure that the number will always use the specified format -- then you can easily extract the day, month and year:
int day = date / 10000;
int month = (date / 100) % 100;
int year = date % 100;
You can do this with modular arithmetic:
int day = date / 10000;
int month = (date / 100) % 100;
int year = date % 100;
Here is the solution in Java with no optimization:
final int value = 111213;
int day;
int month;
int year;
day = value / 10000;
month = (value - (day * 10000)) / 100;
year = (value - (day * 10000)) - month * 100;

Categories

Resources