C# 如果有小数,我如何格式化为仅包含小数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/216538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I format to only include decimal if there are any
提问by Thomas Jespersen
What is the best way to format a decimal if I only want decimal displayed if it is not an integer.
如果我只想显示不是整数的小数,那么格式化小数的最佳方法是什么。
Eg:
例如:
decimal amount = 1000M
decimal vat = 12.50M
When formatted I want:
格式化后我想要:
Amount: 1000 (not 1000.0000)
Vat: 12.5 (not 12.50)
采纳答案by Richard Nienaber
decimal one = 1000M;
decimal two = 12.5M;
Console.WriteLine(one.ToString("0.##"));
Console.WriteLine(two.ToString("0.##"));
回答by Joe
Updated following comment by user1676558
更新了用户 1676558 的以下评论
Try this:
尝试这个:
decimal one = 1000M;
decimal two = 12.5M;
decimal three = 12.567M;
Console.WriteLine(one.ToString("G"));
Console.WriteLine(two.ToString("G"));
Console.WriteLine(three.ToString("G"));
For a decimal value, the default precision for the "G" format specifier is 29 digits, and fixed-point notation is always used when the precision is omitted, so this is the same as "0.#############################".
对于十进制值,“G”格式说明符的默认精度为29位,省略精度时始终使用定点表示法,因此与“0.########相同#####################”。
Unlike "0.##" it will display all significant decimal places (a decimal value can not have more than 29 decimal places).
与“0.##”不同,它会显示所有有效的小数位(小数位不能超过 29 位)。
The "G29" format specifier is similar but can use scientific notation if more compact (see Standard numeric format strings).
“G29”格式说明符类似,但如果更紧凑,可以使用科学记数法(请参阅标准数字格式字符串)。
Thus:
因此:
decimal d = 0.0000000000000000000012M;
Console.WriteLine(d.ToString("G")); // Uses fixed-point notation
Console.WriteLine(d.ToString("G29"); // Uses scientific notation