C# 将小数格式化为两位或整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2148271/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:55:14  来源:igfitidea点击:

Format decimal to two places or a whole number

c#.netstringformatting

提问by Neil

For 10 I want 10 and not 10.00 For 10.11 I want 10.11

对于 10 我想要 10 而不是 10.00 对于 10.11 我想要 10.11

Is this possible without code? i.e. by specifying a format string alone simlar to {0:N2}

这可能没有代码吗?即通过单独指定类似于 {0:N2} 的格式字符串

采纳答案by tvanfosson

decimal num = 10.11M;

Console.WriteLine( num.ToString( "0.##" ) );

回答by GeoffDev

It seems to me that the decimal precision is intrinsic to the decimal type, which defaults to 4 decimal places. If I use the following code:

在我看来,小数精度是小数类型固有的,默认为 4 位小数。如果我使用以下代码:

decimal value = 8.3475M;
Console.WriteLine(value);
decimal newValue = decimal.Round(value, 2);
Console.WriteLine(newValue);

The output is:

输出是:

8.3475
8.35

回答by Mohamed

This can be achieved using CultureInfo. Use the below using statement to import the library.

这可以使用 CultureInfo 来实现。使用以下 using 语句导入库。

using System.Globalization;

For the decimal conversion, ## can be used for optional decimal places and 00 can be used for mandetory decimal places. Check the below examples

对于十进制转换,## 可用于可选小数位,00 可用于强制小数位。检查以下示例

double d1 = 12.12;
Console.WriteLine("Double :" + d1.ToString("#,##0.##", new CultureInfo("en-US")));

String str= "12.09";
Console.WriteLine("String :" + Convert.ToDouble(str).ToString("#,##0.00", new CultureInfo("en-US")));

String str2 = "12.10";
Console.WriteLine("String2 with ## :" + Convert.ToDouble(str2).ToString("#,##0.##", new CultureInfo("en-US")));
Console.WriteLine("String2 with 00 :" + Convert.ToDouble(str2).ToString("#,##0.00", new CultureInfo("en-US")));


int integ = 2;
Console.WriteLine("Integer :" + Convert.ToDouble(integ).ToString("#,##0.00", new CultureInfo("en-US")));

the results are as follows

结果如下

Double :12.12
String :12.09
String2 with ## :12.1
String2 with 00 :12.10
Integer :2.00