C# 显示没有小数点的数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1859507/
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
Displaying numbers without decimal points
提问by user226305
I want to display a number in a report, however I only want to show any decimal points if they are present and the I only want to show 1 decimal space.
我想在报告中显示一个数字,但是我只想显示任何存在的小数点,并且我只想显示 1 个小数位。
e.g. if the number is 12 then I want to show 12
例如,如果数字是 12,那么我想显示 12
If the number is 12.1 then I want to show 12.1
如果数字是 12.1 那么我想显示 12.1
If the number is 12.11 then I want to show 12.1
如果数字是 12.11 那么我想显示 12.1
采纳答案by John Nunn
I had a very similar problem a while ago and the answer is to use a format string when converting the number to a string. The way to solve your issue is to use a custom numeric format string of "0.#"
不久前我遇到了一个非常相似的问题,答案是在将数字转换为字符串时使用格式字符串。解决您的问题的方法是使用“0.#”的自定义数字格式字符串
double x = 12;
double y = 12.1;
double z = 12.11;
Console.WriteLine(x.ToString("0.#"));
Console.WriteLine(y.ToString("0.#"));
Console.WriteLine(z.ToString("0.#"));
Will give you the following output:
将为您提供以下输出:
12
12
12.1
12.1
12.1
12.1
回答by Richard
This will return a number with a single (optional) decimal place.
这将返回一个带有单个(可选)小数位的数字。
String.Format("{0:0.#}", number)
回答by martin
What about
关于什么
Math.Round(12.11,1)?
or
或者
double number = 12.11;
numer.ToString("0.00")