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

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


当前回答

数学舍入方法(十进制,Int32)

其他回答

排名靠前的答案描述了一种格式化十进制值的字符串表示的方法,它是有效的。

但是,如果您确实想将保存的精度更改为实际值,则需要编写如下内容:

public static class PrecisionHelper
{
    public static decimal TwoDecimalPlaces(this decimal value)
    {
        // These first lines eliminate all digits past two places.
        var timesHundred = (int) (value * 100);
        var removeZeroes = timesHundred / 100m;

        // In this implementation, I don't want to alter the underlying
        // value.  As such, if it needs greater precision to stay unaltered,
        // I return it.
        if (removeZeroes != value)
            return value;

        // Addition and subtraction can reliably change precision.  
        // For two decimal values A and B, (A + B) will have at least as 
        // many digits past the decimal point as A or B.
        return removeZeroes + 0.01m - 0.01m;
    }
}

单元测试示例:

[Test]
public void PrecisionExampleUnitTest()
{
    decimal a = 500m;
    decimal b = 99.99m;
    decimal c = 123.4m;
    decimal d = 10101.1000000m;
    decimal e = 908.7650m

    Assert.That(a.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),
        Is.EqualTo("500.00"));

    Assert.That(b.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),
        Is.EqualTo("99.99"));

    Assert.That(c.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),
        Is.EqualTo("123.40"));

    Assert.That(d.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),
        Is.EqualTo("10101.10"));

    // In this particular implementation, values that can't be expressed in
    // two decimal places are unaltered, so this remains as-is.
    Assert.That(e.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),
        Is.EqualTo("908.7650"));
}

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);
}
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

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

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

这是我会使用的:

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

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

https://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx

此链接详细说明了如何处理问题,以及如果您想了解更多信息,可以做什么。为了简单起见,您想做的是

double whateverYouWantToChange = whateverYouWantToChange.ToString("F2");

如果你想要一种货币,你可以通过键入“C2”而不是“F2”来简化