5

How can I set TotalHours to be in double format, or what I need to do to get the result in txtBoxMonatstotal as a result of 93.3. This is my code:

private void calendar1_MonthChanged(object sender, EventArgs e)
{
    DateTime start = new DateTime(calendar1.CurrentDate.Year, calendar1.CurrentDate.Month, 1);
    DateTime stop = new DateTime(calendar1.CurrentDate.Year, calendar1.CurrentDate.Month, 1).AddMonths(1).AddDays(-1);
    int numberOfWorkDays = GetNumberOfWorkingDays(start, stop);

    double shouldWorkPerMonth = tag_durschnit * numberOfWorkDays;
    double workedPerMonth = workingHours.Where(x => x.Key.Date.Year == start.Year && x.Key.Month == start.Month).Sum(x => x.Value.TotalHours);
    double saldo = workedPerMonth - shouldWorkPerMonth;

    txtBoxMonatstotal.Text = workedPerMonth.ToString();
    txtBoxSollzeit.Text = shouldWorkPerMonth.ToString();
    txtBoxSaldo.Text = saldo.ToString();

}

The current result looks like this:
  txtBoxMonatstotal

Thank you for your help

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
Mara
  • 365
  • 1
  • 10
  • 2
    Round the value first before converting it to string. [Math.Round()](https://msdn.microsoft.com/en-us/library/system.math.round(v=vs.110).aspx) – John Woo Jan 22 '18 at 09:02
  • This is what you should do: `Math.Round(workedPerMonth).ToString("N1")`. – Tetsuya Yamamoto Jan 22 '18 at 09:03
  • Or you could just format your output https://stackoverflow.com/questions/1421520/formatting-doubles-for-output-in-c-sharp – BugFinder Jan 22 '18 at 09:03
  • try handling the format : `workedPerMonth.ToString("00.0")` – Mong Zhu Jan 22 '18 at 09:09
  • thanks a lot @MongZhu that's right workedPerMonth.ToString("00.0") – Mara Jan 22 '18 at 09:10
  • do you care about the decimal on the second place? if the value would be `93.39` would you want to print `93.4` ? – Mong Zhu Jan 22 '18 at 09:12
  • 93.4 its ok.. thank you – Mara Jan 22 '18 at 09:15
  • then you need to round first! `workedPerMonth.ToString("00.0")` will give you `93.3` if the value is `93.39`. It will only cut away all decimals after the first decimal place – Mong Zhu Jan 22 '18 at 09:17
  • Possible duplicate of [Calculate relative time in C#](https://stackoverflow.com/questions/11/calculate-relative-time-in-c-sharp) – Lewis86 Jan 22 '18 at 09:59

1 Answers1

1

You need to round the number first and then call ToString on it

txtBoxMonatstotal.Text = System.Math.Round(workedPerMonth, 1).ToString();

the second parameter in Round determines

the number of fractional digits in the return value.

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76