简体   繁体   English

.NET:十进制到圆角字符串

[英].NET: Decimal to rounded string

If I have a decimal , how do I get a string version of it with two decimal places? 如果我有一个decimal ,我怎么得到一个带有两位小数的字符串版本? This isn't working: 这不起作用:

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

Don't use the curly brackets, they are for embedding a formatted value in a longer string using string.Format . 不要使用花括号,它们用于使用string.Format将格式化值嵌入更长的字符串中。 Use this: 用这个:

myDecimal.ToString("0.00");

Maybe i'm wrong, but i've tried myDecimal.ToString(); 也许我错了,但我已经尝试了myDecimal.ToString(); and it worked. 它起作用了。

Assuming myDecimal is a System.Decimal , then Math.Round(myDecimal, 2).ToString(); 假设myDecimalSystem.Decimal ,那么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). 将显示两个精度的十进制数字,如您所愿,没有任何格式字符串(除非您的数字的绝对值大于10 ^ 27-1)。 This is because the decimal datatype retains full precision of the number. 这是因为decimal数据类型保留了数字的完整精度。 That is to say that 1m , 1.0m , and 1.00m are all stored differently and will display differently. 也就是说1m1.0m1.00m都以不同方式存储并且将以不同方式显示。

Note that this is not true of float or double . 请注意, floatdouble不是这样。 1f , 1.0f , and 1.00f are stored and display identically, as do 1d , 1.0d , and 1.00d . 1f1.0f1.00f被存储和显示相同,如1d1.0d1.00d

Since the format string must be parsed at runtime, I would probably omit it for code like this in most cases. 由于格式字符串必须在运行时进行解析,因此在大多数情况下我可能会省略它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM