How do I round a decimal value to 2 decimal places (for output on a page)

When displaying the value of a decimal currently with .ToString() , it's accurate to like 15 decimal places, and since I'm using it to represent dollars and cents, I only want the output to be 2 decimal places.

Do I use a variation of .ToString() for this?


decimalVar.ToString ("#.##"); // returns "" when decimalVar == 0

要么

decimalVar.ToString ("0.##"); // returns "0"  when decimalVar == 0

I know this is an old question, but I was surprised to see that no one seemed to post an answer that;

  • Didn't use bankers rounding
  • Didn't keep the value as a decimal.
  • This is what I would use:

    decimal.Round(yourValue, 2, MidpointRounding.AwayFromZero);
    

    http://msdn.microsoft.com/en-us/library/9s0xa85y.aspx


    decimalVar.ToString("F");
    

    This will:

  • Round off to 2 decimal places eg. 23.456 => 23.46
  • Ensure that there are always 2 decimal places eg. 23 => 23.00, 12.5 => 12.50
  • Ideal for currency and displaying monetary amounts.

    For documentation on ToString("F"): http://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx#FFormatString (with thanks to Jon Schneider)

    链接地址: http://www.djcxy.com/p/21362.html

    上一篇: 用JavaScript获取数字的小数部分

    下一篇: 如何将十进制值舍入为2个小数位(用于页面上的输出)