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

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


当前回答

如果您希望使用逗号和小数点(但不使用货币符号)格式化,例如3456789.12。。。

decimalVar.ToString("n2");

其他回答

我知道这是一个古老的问题,但我惊讶地发现似乎没有人发布这样的答案;

没有使用银行家舍入将值保留为小数。

这是我会使用的:

decimal.Round(yourValue, 2, MidpointRounding.AwayFromZero);

http://msdn.microsoft.com/en-us/library/9s0xa85y.aspx

Mike M.的答案对我来说非常适合.NET,但在撰写本文时,.NET核心没有十进制舍入方法。

在.NET Core中,我必须使用:

decimal roundedValue = Math.Round(rawNumber, 2, MidpointRounding.AwayFromZero);

一种包括转换为字符串在内的黑客方法是:

public string FormatTo2Dp(decimal myNumber)
{
    // Use schoolboy rounding, not bankers.
    myNumber = Math.Round(myNumber, 2, MidpointRounding.AwayFromZero);

    return string.Format("{0:0.00}", myNumber);
}

如果值为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分钟的时间。

给定小数d=12.345;表达式d.ToString(“C”)或String.Format(“{0:C}”,d)产生$12.35-请注意,使用了当前区域性的货币设置,包括符号。

请注意,“C”使用当前区域性中的位数。您可以始终使用C{precision说明符}(如String.Format(“{0:C2}”,5.123d))重写默认值以强制执行必要的精度。

        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。