我想要的是10而不是10.00
我想要的是10.11,这可否在不使用代码的情况下实现?例如通过仅指定格式字符串,类似于 {0:N2}。
我想要的是10而不是10.00
我想要的是10.11,这可否在不使用代码的情况下实现?例如通过仅指定格式字符串,类似于 {0:N2}。
decimal num = 10.11M;
Console.WriteLine( num.ToString( "0.##" ) );
num % 1 == 0 ? num.ToString("0") : num.ToString("0.00");
这段代码?你可以将其实现为 decimal 的扩展方法。 - tvanfossondecimal.Truncate(num) == num
而不是模1的方法。 - tvanfosson我认为十进制精度是固有于十进制类型的,它的默认值为4位小数。如果我使用以下代码:
decimal value = 8.3475M;
Console.WriteLine(value);
decimal newValue = decimal.Round(value, 2);
Console.WriteLine(newValue);
8.3475
8.35
可以使用CultureInfo来实现。使用以下using语句导入库。
using System.Globalization;
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
decimal
,然后使用格式化字符串"#,##0.##"
的ToString
方法。decimal a = 5000000;
decimal b = 5000;
decimal c = 5;
decimal d = 2.5m;
decimal e = 0.0005m;
decimal f = 0.45m;
decimal g = 0.499m;
decimal h = 0.51515m;
decimal i = 123456.789m;
decimal j = 10.1m;
// Answers in my English localization
string format = "#,##0.##";
Console.WriteLine("a=" + a.ToString(format)); // 5,000,000
Console.WriteLine("b=" + b.ToString(format)); // 5,000
Console.WriteLine("c=" + c.ToString(format)); // 5
Console.WriteLine("d=" + d.ToString(format)); // 2.5
Console.WriteLine("e=" + e.ToString(format)); // 0
Console.WriteLine("f=" + f.ToString(format)); // 0.45
Console.WriteLine("g=" + g.ToString(format)); // 0.5
Console.WriteLine("h=" + h.ToString(format)); // 0.52
Console.WriteLine("i=" + i.ToString(format)); // 123,456.79
Console.WriteLine("j=" + j.ToString(format)); // 10.1
如果您需要保留两位小数,可以使用"#,##0.00"
,但是这将始终显示整数的 .00。