Search code examples
c#asp.net-mvcc#-4.0doublerazor-2

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


Solution

  • 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.