c# 中四舍五入到小数点后两位

问题描述 投票:0回答:9

如何将两位小数相乘并将结果四舍五入到小数点后两位?

例如,如果方程为 41.75 x 0.1,则结果将为 4.175。如果我在 C# 中使用小数执行此操作,它将自动四舍五入到 4.18。我想四舍五入到 4.17。

我尝试使用 Math.Floor,但它只是向下舍入到 4.00。这是一个例子:

Math.Floor (41.75 * 0.1);
c# decimal rounding
9个回答
69
投票

Math.Round(...)
函数有一个枚举来告诉它使用什么舍入策略。不幸的是,这两个定义并不完全适合您的情况。

两种中点舍入模式是:

  1. AwayFromZero - 当一个数字介于其他两个数字之间时,它会向远离零的最接近的数字舍入。 (又名,四舍五入)
  2. ToEven - 当一个数字介于另外两个数字之间时,它会向最接近的偶数舍入。 (相对于 0.17 更倾向于 0.16,相对于 0.17 更倾向于 0.18)

你想要使用的是

Floor
和一些乘法。

var output = Math.Floor((41.75 * 0.1) * 100) / 100;

output
变量现在应该有 4.17。

事实上,您也可以编写一个函数来获取可变长度:

public decimal RoundDown(decimal i, double decimalPlaces)
{
   var power = Convert.ToDecimal(Math.Pow(10, decimalPlaces));
   return Math.Floor(i * power) / power;
}

19
投票
public double RoundDown(double number, int decimalPlaces)
{
     return Math.Floor(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);
}

17
投票

截至

.NET Core 3.0
和即将到来的
.NET Framework 5.0
以下内容有效

Math.Round(41.75 * 0.1, 2, MidpointRounding.ToZero)

9
投票

c# 中没有对精确地板/天花板的本机支持。

但是,您可以通过乘以数字、下限,然后除以相同的乘数来模拟该功能。

例如,

decimal y = 4.314M;
decimal x = Math.Floor(y * 100) / 100;  // To two decimal places (use 1000 for 3 etc)
Console.WriteLine(x);  // 4.31

不是理想的解决方案,但如果数量很小,应该可以工作。


1
投票

还有一个解决方案是从远离零舍入到向零舍入。 应该是这样的:

    static decimal DecimalTowardZero(decimal value, int decimals)
    {
        // rounding away from zero
        var rounded = decimal.Round(value, decimals, MidpointRounding.AwayFromZero);

        // if the absolute rounded result is greater 
        // than the absolute source number we need to correct result
        if (Math.Abs(rounded) > Math.Abs(value))
        {
            return rounded - new decimal(1, 0, 0, value < 0, (byte)decimals);
        }
        else
        {
            return rounded;
        }
    }

1
投票

如果您想将任何双精度数向下舍入到特定的小数位,如果中点并不重要,您可以使用:

    public double RoundDownDouble(double number, int decimaPlaces)
    {
        var tmp = Math.Pow(10, decimaPlaces);
        return Math.Truncate(number * tmp) / tmp;
    }

0
投票

这是我的防浮圆向下。

    public static class MyMath
{
    public static double RoundDown(double number, int decimalPlaces)
    {
        string pr = number.ToString();
        string[] parts = pr.Split('.');
        char[] decparts = parts[1].ToCharArray();
        parts[1] = "";
        for (int i = 0; i < decimalPlaces; i++)
        {
            parts[1] += decparts[i];
        }
        pr = string.Join(".", parts);
        return Convert.ToDouble(pr);
    }
}

0
投票

我发现最好的方法是使用字符串;数学的二进制变幻莫测往往会出错,否则。人们等待 .Net 5.0 来消除这一事实。没有小数位是一种特殊情况:您可以使用 Math.Floor 来实现这一点。否则,我们将比所需小数位多一位的数字转换为字符串,然后解析该数字(去掉最后一位数字)以获得答案:

/// <summary>
/// Truncates a Double to the given number of decimals without rounding
/// </summary>
/// <param name="D">The Double</param>
/// <param name="Precision">(optional) The number of Decimals</param>
/// <returns>The truncated number</returns>
public static double RoundDown(this double D, int Precision = 0)
{
  if (Precision <= 0) return Math.Floor(D);
  string S = D.ToString("0." + new string('0', Precision + 1));
  return double.Parse(S.Substring(0, S.Length - 1));
}

-1
投票

简单地

Math.Round()
解决了这个问题,并通过向方法传递
precision
参数和
MidpointRounding
参数来适应这种情况。

简短的回答是:

Math.Round(41.75 * 0.1, 2, MidpointRounding.ToNegativeInfinity)

其中第二个参数是精度,第三个参数是舍入策略。

如果您想确切了解

Math.Round
的工作原理,您可以在此处阅读完整说明: 如何在 C# 中将数字四舍五入到小数点后两位?

© www.soinside.com 2019 - 2024. All rights reserved.