将小数格式化为两个位置或整数

时间:2010-01-27 15:46:17

标签: c# .net string formatting

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

这可能没有代码吗?即通过单独指定格式字符串 {0:N 2}

3 个答案:

答案 0 :(得分:46)

decimal num = 10.11M;

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

答案 1 :(得分:3)

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

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

输出结果为:

8.3475
8.35

答案 2 :(得分:0)

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

using System.Globalization;

对于十进制转换,##可以用于可选的小数位,而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")));

结果如下

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