当显示当前使用.ToString()的十进制值时,它精确到15位小数,因为我使用它来表示美元和美分,所以我只希望输出为2位小数。

我是否为此使用.ToString()的变体?


当前回答

最适用的解决方案是

decimalVar.ToString("#.##");

其他回答

Double Amount = 0;
string amount;
amount=string.Format("{0:F2}", Decimal.Parse(Amount.ToString()));
        var arr = new List<int>() { -4, 3, -9, 0, 4, 1 };
        decimal result1 = arr.Where(p => p > 0).Count();
        var responseResult1 = result1 / arr.Count();
        decimal result2 = arr.Where(p => p < 0).Count();
        var responseResult2 = result2 / arr.Count();
        decimal result3 = arr.Where(p => p == 0).Count();
        var responseResult3 = result3 / arr.Count();
        Console.WriteLine(String.Format("{0:#,0.000}", responseResult1));
        Console.WriteLine(String.Format("{0:#,0.0000}", responseResult2));
        Console.WriteLine(String.Format("{0:#,0.00000}", responseResult3));

你可以放任意多的0。

您可以使用system.globalization以任何所需格式格式化数字。

例如:

system.globalization.cultureinfo ci = new system.globalization.cultureinfo("en-ca");

如果您有一个小数d=1.2300000,并且需要将其修剪为2位小数,则可以像这样打印d.Tostring(“F2”,ci);其中F2是字符串格式,小数点后2位,ci是区域设置或文化信息。

有关详细信息,请查看此链接http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

decimalVar.ToString("#.##"); // returns ".5" when decimalVar == 0.5m

or

decimalVar.ToString("0.##"); // returns "0.5"  when decimalVar == 0.5m

or

decimalVar.ToString("0.00"); // returns "0.50"  when decimalVar == 0.5m

如果值为0,则很少需要空字符串。

decimal test = 5.00;
test.ToString("0.00");  //"5.00"
decimal? test2 = 5.05;
test2.ToString("0.00");  //"5.05"
decimal? test3 = 0;
test3.ToString("0.00");  //"0.00"

排名最高的答案是错误的,浪费了(大多数)人10分钟的时间。