我想用数学来做。圆的函数


当前回答

下面是一些例子:

decimal a = 1.994444M;

Math.Round(a, 2); //returns 1.99

decimal b = 1.995555M;

Math.Round(b, 2); //returns 2.00

你可能还想看看银行家的四舍五入/四舍五入到偶数与以下过载:

Math.Round(a, 2, MidpointRounding.ToEven);

这里有更多的信息。

其他回答

有一个奇怪的情况,我有一个十进制变量,当序列化55.50时,它总是设置数学默认值为55.5。但是,由于某些原因,我们的客户端系统期望的是55.50,他们肯定期望的是十进制。这就是当我写下面的帮助,它总是转换任何十进制值填充到2位零,而不是发送一个字符串。

public static class DecimalExtensions
{
    public static decimal WithTwoDecimalPoints(this decimal val)
    {
        return decimal.Parse(val.ToString("0.00"));
    }
}

用法应该是

var sampleDecimalValueV1 = 2.5m;
Console.WriteLine(sampleDecimalValueV1.WithTwoDecimalPoints());

decimal sampleDecimalValueV1 = 2;
Console.WriteLine(sampleDecimalValueV1.WithTwoDecimalPoints());

输出:

2.50
2.00

试试这个:

twoDec = Math.Round(val, 2)

您应该能够使用Math指定要舍入的位数。轮(YourNumber, 2)

你可以在这里阅读更多。

如果你想要一根绳子

> (1.7289).ToString("#.##")
"1.73"

或者小数

> Math.Round((Decimal)x, 2)
1.73m

但请记住!舍入不是分配的。圆(x*y) !=圆(x) *圆(y)。所以在计算结束之前不要做任何舍入运算,否则会失去精度。

字符串a = "10.65678";

decimal d = Math.Round(Convert.ToDouble(a.ToString()),2)