locked
2 Decimal Places on my label RRS feed

  • Question

  • User-1901014284 posted

    Hi,

    I am using the below code to calculate the total cost of a consultants work duration minutes by the consultants hourly rate.

    What I would like to do is round the decimal figure to 2 decimal places to get the correct calculation. I have tried adding the Math.Round workaround bit this has not worked for me also. the figure within the label still displays all carried over figuere (e.g. 1.666666666666667 I want it to be 1.67)

    string result = TotalTravelStartMinutesLabel0.Text;
    int WDC = int.Parse(result);
    decimal PM = Decimal.Parse(PerMinuteLabel.Text);
    Math.Round(PM, 2);
    DurationCostLabel.Text = (WDC * (decimal)PM).ToString("C");

    Any help would be greatly appreciated.

    Many thanks

    Jonny

    Monday, July 31, 2017 1:20 PM

Answers

All replies

  • User475983607 posted

    it is unclear of you are concerned with significant figures or simply formatting a number as a string.  This line of code should show decimal places according your the culture setting.

    DurationCostLabel.Text = (WDC * (decimal)PM).ToString("C");

    Monday, July 31, 2017 1:51 PM
  • User-1901014284 posted

    Thank you for responding, I would like to format the decimal figure to only 2 decimal places. Would this be possible?

    Monday, July 31, 2017 2:19 PM
  • User475983607 posted

    Thank you for responding, I would like to format the decimal figure to only 2 decimal places. Would this be possible?

    Sill not clear. The "C" format string will convert the result to currency as described on the following reference doc.

    https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings

    This code

    decimal value = 1.666667m;
    Console.WriteLine((10.0m * value).ToString("C"));

    results in 

    $16.67

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 31, 2017 2:32 PM
  • User-1901014284 posted

    Hi,

    Thank you very much for your response, to get this to work as I require I have had to set the format on the label itself after parsing the result to the label. Please see below my code which I have used as a work around.

    double Perminresult = double.Parse(HourlyRateLabel.Text) / 60;
    PerMinuteLabel.Text = Perminresult.ToString("##.##");

    Again thank you very much for your help it has been greatly appreciated.

    Many thanks

    Jonny

    Tuesday, August 1, 2017 10:40 AM