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;
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:
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获取数字的小数部分