Andrus
Andrus

Reputation: 27955

how to print double using rounded number of decimals

C# 4.0 ASP.NET MVC4 application contains Out method called from Razor views. It receives rounded double as parameter.

protected static string Out( double roundedValue ) {
  return roundedValue.ToString();  
}

it should return number of decimal places into which value is rounded to show in view. E.q

Out( Math.Round(1.2f, 2));

should return 1.20

and

Out( Math.Round(1.2f,3 ));

should return 1.200

Actually first call returns 1.2 . It looks like trailing zeroes are removed by ToString(). How to force Out method to return number of decimal places specified in Round call,

e.q

Out( Math.Round(1.2f, 2));

should return 1.20

Upvotes: 0

Views: 1924

Answers (2)

alstonp
alstonp

Reputation: 700

You are mistaken by the concept of rounding a number and displaying a value. Math.Round() only rounds to the number of decimal places that you are using. It has no effect on the number of decimal places the .Tostring() function puts at the end. You will need to use the following formatting to output the way you want:

    float number = 1.23f;
    Console.WriteLine(number.ToString("0.000")); //1.230
    Console.WriteLine(number.ToString("0.00"));  //1.23
    Console.WriteLine(number.ToString("0.0"));   //1.2

Please see the MSDN page on .ToString() Formatting if you want to see more. :)

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502156

It's important to understand that float and double don't retain trailing zeroes. You have two options:

  • Specify the format to include the number of decimal places you're interested in
  • Use decimal, which does retain trailing zeroes

It's not clear from your question which option is the most appropriate. If this is a currency value (e.g. a price) then you should definitely be using decimal.

Upvotes: 1

Related Questions