Convert string to int to display delimted time using Split - c#

This is an attempt to convert a split string to an int format to display a user input time such as 2:15 meaning 2 hours and 15 minutes. I want to be able to multiply this time period by a dollar rate and add an additional cost. there is a subAmount and then a total both using ToString. Any 'clues' would be appreciated
private void calulateButton_Click(object sender, EventArgs e)
{
string[] item = timeTextBox.Text.Split(':');
int hours, mins, rate, cost;
int.TryParse(item[0], out hours);
Convert.ToInt64(item[0]);
int.TryParse(item[1], out hours);
Convert.ToInt64(item[1]);
int.TryParse(rateTextBox.Text, out rate);
int.TryParse(prescriptionTextBox.Text, out cost);
int prescription = cost;
int totalHours = hours;
subAmountLabel.Text = totalHours.ToString("f2");
int total = (totalHours) * rate + cost;
totalAmountLabel.Text = total.ToString("f2");
}

This is just a shot in the dark at what I think you are trying to do:
TimeSpan ts = TimeSpan.Parse(timeTextBox.Text);
double rate, cost;
double.TryParse(rateTextBox.Text, out rate);
double.TryParse(prescriptionTextBox.Text, out cost);
subAmountLabel.Text = ts.TotalHours.ToString("f2");
double total = ts.TotalHours * rate + cost;
totalAmountLabel.Text = total.ToString("f2");

You code sample seems perfectly valid (except you assign hours twice) but it contains some redundant lines. I fixed issue with hours and mins, got rid of unnecessary variables and instructions and edited total formula to include minutes as well:
private void calulateButton_Click(object sender, EventArgs e)
{
string[] item = timeTextBox.Text.Split(':');
int hours, mins;
int.TryParse(item[0], out hours);
int.TryParse(item[1], out mins);
double rate, prescription;
double totalHours = hours + mins / 60.0;
double.TryParse(rateTextBox.Text, out rate);
double.TryParse(prescriptionTextBox.Text, out prescription);
double total = totalHours * rate + prescription;
subAmountLabel.Text = totalHours.ToString("G");
totalAmountLabel.Text = total.ToString("C");
}

Related

Converting time input from 24hr clock , to seconds, and back to 24 hr format

What I need to do is take a time window on a 24hr clock ie: 1000-1100
convert it to seconds, which I can do.
(1000 / 100)*60 = 600
(1100 / 100)*60 = 660
Get 25% of the result(15), which I can also do. (660 / 4)
Add that 25% of additional seconds to the previous end time (1100)
The issue is that I am getting an output of 1100 instead of 1115
The Question is how do I make it output as 1115.
I do use constants to define hour and hundred so no magic numbers, these numbers are just illustrating the math.
//define constants
const int HUNDRED = 100;
const int HOUR = 60;
const int PERCENT = 4;
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
// recieve start time input
string oldStart = oldStartTime.Text;
int oldTimeIn = int.Parse(oldStart);
// recieve end time input
string oldEnd = oldEndTime.Text;
int oldTimeEnd = int.Parse(oldEnd);
// convert start time to minutes
int hoursStart = (oldTimeIn / HUNDRED) * HOUR;
int minutesStart = oldTimeIn % HUNDRED;
int totalStart = hoursStart + minutesStart;
// convert end time to minutes
int hoursEnd = (oldTimeEnd / HUNDRED) * HOUR;
int minutesEnd = oldTimeEnd % HUNDRED;
int totalEnd = hoursEnd + minutesEnd;
// calulate 25% of travel time ( end - start )
int extraTime = totalEnd - totalStart;
int totalMinutes = (extraTime / PERCENT);
// convert back to hours
int newEndHours = (totalEnd + totalMinutes) / HOUR * HUNDRED;
// out put new end time
newEndTime.Text = $"{newEndHours:d4}";
int newEndHours = (totalEnd + totalMinutes) / HOUR * HUNDRED;
The operation is being done as integers, so the (660 + 15)/100 is coming out as 11. Remember that even if it was casted to doubles, it would result in 11.25, and not 11.15.
You will have to add in another part similar to when you deconstructed the time to handle the minutes part, so
int newEndHours = (totalEnd + totalMinutes) / HOUR * HUNDRED + (totalEnd + totalMinutes) % HOUR;

Loop to calculate organism growth

I am trying to make a loop that calculates number of organisms over time, but I am stuck on how to make the loop update. Do I need to put something outside the for loop to update the total organisms?
private void calculateButton_Click(object sender, EventArgs e)
{
//declare variables for number of days passed and population
double days;
double organisms;
double increaseDaily;
double total_organisms;
//declare the constants to be used
const int interval = 1;
const int start_days = 1;
//try parse to get amount of starting organisms
if (double.TryParse(organismTextBox.Text, out organisms))
{
//try parse to get the percent daily increase
if (double.TryParse(dailyIncreaseTextBox.Text, out increaseDaily))
{
//try parse to get the number of days passed
if (double.TryParse(daysMultiplyTextBox.Text, out days))
{
//for loop to count through the number of days
for (int i = 1; i <= days; i += interval)
{
//calculate the amount of organisms
total_organisms = (organisms * (increaseDaily / 100) + organisms);
//display the amount of organisms after an amount of time
listBox1.Items.Add("after " + i + " days, the amount of organisms is " + total_organisms);
}
Each loop, you are calculating the total_organisms as the sum of organisms plus some percent:
total_organisms = (organisms * (increaseDaily / 100) + organisms);
You are never changing the value of organisms, so total_organisms will be calculated as the same value each loop. You should just updated the value of organisms instead.
Also, you could reduce indentation in your code by changing each if statement to test for parse failure and bail out:
private void calculateButton_Click(object sender, EventArgs e)
{
//declare variables for number of days passed and population
double days;
double organisms;
double increaseDaily;
List<string> errors = new List<string>();
//declare the constants to be used
const int interval = 1;
const int start_days = 1;
//try parse to get amount of starting organisms
if (!double.TryParse(organismTextBox.Text, out organisms)) {
errors.Add("Organisms must be a valid number");
}
//try parse to get the percent daily increase
if (double.TryParse(dailyIncreaseTextBox.Text, out increaseDaily)) {
errors.Add("Daily increase must be a valid number");
}
//try parse to get the number of days passed
if (double.TryParse(daysMultiplyTextBox.Text, out days)) {
errors.Add("Number of days must be a valid number");
}
if (errors.Any()) {
// Display errors to user here (depending on your UI)
return;
}
//for loop to count through the number of days
for (int i = 1; i <= days; i += interval) {
//calculate the amount of organisms
organisms = (organisms * (increaseDaily / 100) + organisms);
//display the amount of organisms after an amount of time
listBox1.Items.Add(
"after " + i + " days, the amount of organisms is " + organisms);
}
}
If you want to keep adding to the total number of organisms:
total_organisms = total_organisms + (organisms * (increaseDaily / 100) + organisms);

i need to add two variables together for a messagebox/textbox for a programming project IN C#

hey all so I'm having a hard time with my code when trying to display in a textbox.. testing goes well till i try something along the lines of a start time being a higher number than the end time when i do it displays something like this on my program -04-30 but on the example program it shows -0430.
How can i get it to display properly?
My last three lines of code read. (this is for a programming project for my college class. i have my form program i have developed and then an example one. for the program it asks to give a start time, and end time. and the program calculates a new arrival time due to construction in the area(which makes the original trip 25% longer)
int endTimeHours = (int) totalTimeMins / DIVISOR_SIXTY;
int endTimeMins = (int)totalTimeMins - (endTimeHours * DIVISOR_SIXTY);
//display answer in textbox for user to see and understand.
textBoxNewArrival.Text = string.Format("{0:d2}" + "{1:d2}", endTimeHours, endTimeMins);
entire code is;
`// Declare Constants
const int HUNDRED = 100, DIVISOR_SIXTY = 60;
const double CONSTRUCTION = 1.25;
//get start time from user
int startTime = int.Parse(textBoxStart.Text);
//get end time from user
int endTime = int.Parse(textBoxEnd.Text);
//separate and convert to hours and minutes for start time
int hoursStart = startTime / HUNDRED;
int minsStart = startTime % HUNDRED;
int totalMinutesStart = (hoursStart * DIVISOR_SIXTY) + minsStart;
//separate and convert to hours and minutes for end time
int hoursEnd = endTime / HUNDRED;
int minEnd = endTime % HUNDRED;
int totalMinutesEnd = (hoursEnd * DIVISOR_SIXTY) + minEnd;
//find total duration by subtracting total end times in minutes from total start time in minutes
int totalDuration = totalMinutesEnd - totalMinutesStart;
//take the totalDuration or time between start and end and multiply by 1.25 for construction time.
double construction = totalDuration * CONSTRUCTION;
//take totalmintuesstart from begining and add construction.
double totalTimeMins = totalMinutesStart + construction;
//find and convert the answers into hours and minutes total
int endTimeHours = (int) totalTimeMins / DIVISOR_SIXTY;
int endTimeMins = (int) totalTimeMins - (endTimeHours * DIVISOR_SIXTY);
//display answer in textbox for user to see and understand.
textBoxNewArrival.Text = string.Format("{0:d2}" + "{1:d2]", endTimeHours, endTimeMins.ToString().Remove(0, 1));
`
Just keep the sign of the first value, and always use the absolute value of the second?
textBoxNewArrival.Text = string.Format("{0:d2}" + "{1:d2}", endTimeHours, Math.Abs(endTimeMins));
For a quick solution you should try doing this in the textBox assignation:
textBoxNewArrival.Text = string.Format("{0:d2}" + "{1:d2}", int.Parse(endTimeHours, endTimeMins.ToString().Remove(0,1)));
this is the test i did to check if this time worked:
class Forms
{
public static void Main(string[] args)
{
int endTimeHours = -4;;
int endTimeMins = -30;
string temp = string.Format("{0:d2}" + "{1:d2}", endTimeHours, int.Parse(endTimeMins.ToString().Remove(0, 1)));
Console.WriteLine(temp);
}
}

Text box string not recognized as valid DateTime

const double PERCENT = 0.25;
DateTime t1 = Convert.ToDateTime(txtB_StartT.Text);
DateTime t2 = Convert.ToDateTime(txtB_EndT.Text);
TimeSpan ts = t1.Subtract(t2);
I cant seem to get this to parse into a DateTime
double tsMin = Convert.ToDouble(ts);
double tsMinTot = ts.TotalMinutes;
short tsMinPercent = (short)(((double)tsMinTot) * PERCENT);
double tsAndPercentTot = tsMinPercent + tsMinTot;
My goal here was to find a timediff, find what 25% of that timediff is and add it to the timediff.
DateTime newTimeMinTot = Convert.ToDateTime(tsAndPercentTot);
int hours = newTimeMinTot.Hour;
int minutes = newTimeMinTot.Minute;
An attempt to get a calculated new Datetime
string newTimeStrg = string.Format("{0:d1}:{1:d2}", hours, minutes);
txtB_NewDelivT.Text = newTimeStrg;
Attempt to output new DateTime to TextBox.
Someone please explain. How can I make the user input in military time and make this work.
Do it like this:
const double PERCENT = 0.25;
DateTime t1 = Convert.ToDateTime(txtB_StartT.Text);
DateTime t2 = Convert.ToDateTime(txtB_EndT.Text);
TimeSpan ts = t1.Subtract(t2);
long tsMinPercent = ts.Ticks + (long)(ts.Ticks * PERCENT);
var tsAndPercentTot = TimeSpan.FromTicks(tsMinPercent);
string newTimeStrg = string.Format("{0:d1}:{1:d2}", tsAndPercentTot.Hours, tsAndPercentTot.Minutes);
txtB_NewDelivT.Text = newTimeStrg;
Here I am using DateTime.Ticks to calculate percentage of time of difference and TimeSpan.FromTicks to find DateTime again from calculated percentage DateTime.
Instead using TextBox you can use TimePicker.
to force your date/datetime format
DateTime mydate = DateTime.ParseExact(TextBox1.Text.Trim(), "dd/MM/yyyy", null);
Based on your comment where you write that the input values are "0945" and "1445", I suggest you to replace your TextBox controls with DateTimePicker controls.
Just to have them display values as you are doing right now, you'll have to set some properties as I show you here.
picker.Format = DateTimePickerFormat.Custom;
picker.CustomFormat = "HHmm";
picker.ShowUpDown = true;
later, the picker.Value will return a whole date with time, where minutes and seconds will resemble the input values.
You can obvously set the properties' values from the designer.
Regards,
Daniele.
Since I don't have your form, I'll leave out the UI interaction. Here's how you can parse an input stream. I've show how to parse a hh:mm format, as well as a hhmm format:
var start = TimeSpan.ParseExact("10:00", "hh\\:mm", CultureInfo.InvariantCulture);
var finish = TimeSpan.ParseExact("1100", "hhmm", CultureInfo.InvariantCulture);
Once you have the start and finish, all we have to do is the math. We'll create a new TimeSpan from the ticks (the smallest unit of measurement on a TimeSpan) multiplied by our percentage (0.25). Then we just add the adjustment to our start time and we're done! You can then assign that into where ever you need the output.
var diff = finish - start;
var adjustment = TimeSpan.FromTicks((long)(diff.Ticks * 0.25));
var adjustedStart = start + adjustment;
You can run the code out at dotNetFiddle. I've included output there so you can see the intermediate results along the way.
Ok well i took a different approach and it worked out fairly easy.
I'm not sure if I'm allowed to answer my own question but i figure it
will help someone with the same issue i had.
// Set Constant values.
const double PERCENT = .25;
const int HUN_PART = 100, SIXTY = 60, one = 1;
// Parse start time textbox value as int
// Calculate start time hours and minutes
int sT = int.Parse(textBox1.Text);
int sH = sT / HUN_PART;
int sM = sT % HUN_PART;
// Calculate total start time in minutes
int sH_M = sH * SIXTY;
int sTotM = sH_M + sM;
// Parse end time textbox value as int
// Calculate end time hours and minutes
int eT = int.Parse(textBox2.Text);
int eH = eT / HUN_PART;
int eM = eT % HUN_PART;
// Calculate total end time in minutes
int eH_M = eH * SIXTY;
int eTotM = eH_M + eM;
// Calculate time difference in minutea
// Calculate percent of time difference
double dT_M = Convert.ToInt32(eTotM - sTotM);
int perc = Convert.ToInt32(dT_M * PERCENT);
// Calculate new arrival time in total min then in hours
double newD_M = perc + eTotM;
double newD_H = newD_M / SIXTY;
// Calculate new arrivaltime in remaining minutes
double nD_H_Convert = Math.Truncate(newD_H);
int nD_H = Convert.ToInt32(nD_H_Convert);
int nD_Hours = nD_H * HUN_PART;
double nD_Min = nD_H * SIXTY;
int nD_M = Convert.ToInt32(newD_M - nD_Min);
int newDeliveryTime = (nD_H * HUN_PART) + nD_M;
// Put values for new arive time hours and minutes in appropriate string format
string newTime = string.Format("{0:d4}", newDeliveryTime);
// Output arrival time string in textbox
textBox3.Text = newTime;
I was apparently trying to do more than was actually required, so by using a few simple calculations the issue was resolved.
Thank you for the help everyone.

Progressive loop calculations

Ok. So I'm trying to have a program.. where the user enters his salary and then the program will calculate his salary for the next four years with a raise of 2.5% each year.
I feel like I have done this completely wrong, because my loop is only calculating one time.. its not even showing four salary's.. not to mention having them each raised 2.5% each time.
private void btnDisplay_Click(object sender, EventArgs e)
{
int count;
for (count = 1; count <= 4; count++)
{
decimal Raise;
decimal Salary;
decimal Sum;
decimal Total;
Raise = Convert.ToDecimal(0.025);
Salary = Convert.ToDecimal(txtSalary.Text);
Sum = Salary * Raise;
Total = Salary + Sum;
label2.Text = Total.ToString("c");
}
txtSalary is whatever the user entered salary is.
label2 is the display of the calculation.
---------------- UPDATE: I have updated the code with the final product. Thanks to everyone for helping out especially Patrick Hofman! You are the best.. I couldn't have done it without you. ------------------------
private void btnDisplay_Click(object sender, EventArgs e)
{
decimal salary = Convert.ToDecimal(txtSalary.Text);
decimal raise = 0.025m;
decimal previous = salary;
for (decimal year = 1; year <= 4; year++)
{
decimal sum = previous * (1 + raise);
previous = sum;
listBox1.Items.Add(sum.ToString("c"));
}
I think you should have something like this:
private void btnDisplay_Click(object sender, EventArgs e)
{
decimal salary = Convert.ToDecimal(txtSalary.Text);
decimal raise = 0.025m;
decimal total = 0;
decimal previous = salary;
listBox1.Items.Add("Start: {0:N2}", salary);
for (int year = 1; year <= 4; year++)
{
decimal sum = previous * (1 + raise);
previous = sum;
total += sum;
listBox1.Items.Add("Year {0}: {1:N2}", year, sum);
}
listBox1.Items.Add("Total: {0:N2}", total);
}
Note I made some changes to the variables. Some were moved to keep them over the for loop.
The steps:
Start with setting the start point (previous) to the salary.
For each year, multiply the previous year's salary with the raise percentage +1.
Set the previous and add that year's salary to the total.
Show the total in the label.
int count;
Salary = Convert.ToDecimal(txtSalary.Text);
for (count = 1; count <= 4; count++)
{
Salary *= 1.025m;
}
label2.Text = Salary.ToString("c");
You need to make sure you're retrieve the salary once at teh beginning and don't overwrite it till the end.
Problem 1: You are declaring the variables inside the forloop.so each time they are initialised with their default values.
Solution 1: inorder to retain their last assigned values you need to move the declaration of the variables outside the loop.
Problem 2: you are not able to see the results/changes as you are updating the label inside the for loop without any delay.so evatually you can only see the last calculated result.
Solution2: You need to either create 4 different labels to show the 4 different results or you need to wait for some time for updating the label results in each iteration by using timer functionality.
Try This: using LabelArray
Label[] lblSalaries = new Label[4];
private void CreateControls()
{
int x = 0, y = 10;
for (int i = 0; i < lblSalaries.Length;i++ )
{
lblSalaries[i] = new Label();
x += 60;
lblSalaries[i].Size = new System.Drawing.Size(50, 30);
lblSalaries[i].Location = new System.Drawing.Point(x,y);
Controls.Add(lblSalaries[i]);
}
}
private void btnDisplay_Click(object sender, EventArgs e)
{
int count;
decimal Raise;
decimal Salary;
decimal Sum;
decimal Total;
CreateControls();
for (count = 1; count <= 4; count++)
{
Raise = Convert.ToDecimal(0.025);
Salary = Convert.ToDecimal(txtSalary.Text);
Sum = Salary * Raise;
Total = Salary + Sum;
lblSalaries[count-1].Text = Total.ToString("c");
}
}

Categories