.NET: Decimal to rounded string

佐手、 提交于 2019-12-12 11:23:47

问题


If I have a decimal, how do I get a string version of it with two decimal places? This isn't working:

Math.Round(myDecimal, 2).ToString("{0.00}");

回答1:


Don't use the curly brackets, they are for embedding a formatted value in a longer string using string.Format. Use this:

myDecimal.ToString("0.00");



回答2:


Maybe i'm wrong, but i've tried myDecimal.ToString(); and it worked.




回答3:


Assuming myDecimal is a System.Decimal, then Math.Round(myDecimal, 2).ToString(); will display two decimal digits of precision, just as you want, without any format string (unless the absolute value of your number is greater than 10^27-1). This is because the decimal datatype retains full precision of the number. That is to say that 1m, 1.0m, and 1.00m are all stored differently and will display differently.

Note that this is not true of float or double. 1f, 1.0f, and 1.00f are stored and display identically, as do 1d, 1.0d, and 1.00d.

Since the format string must be parsed at runtime, I would probably omit it for code like this in most cases.



来源:https://stackoverflow.com/questions/2141703/net-decimal-to-rounded-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!