【问题标题】:Rounding Off a double value using Math.Round使用 Math.Round 对双精度值进行四舍五入
【发布时间】:2020-03-02 18:26:36
【问题描述】:

我有一个双精度值:0.314285,我想将其四舍五入到小数点后 5 位。从数学的角度来看,我的预期结果是:0.31429。在我的代码中,我使用带有 MidPointRounding.AwayFromZero 参数重载的 Math.Round,结果输出为:0.31428。

还有其他方法可以实现输出结果为:0.31429??

【问题讨论】:

  • 您是如何声明0.314285 值的?基本上,您应该阅读此article 使用小数将解决您的问题
  • @Sнаđошƒаӽ 这与MidpointRounding有关,Round默认使用MidpointRounding.IsEven,但OP明确将其设置为AwayFromZero

标签: c# .net


【解决方案1】:

您应该阅读rounding and precision 文章。您的号码在内存中的真实表示可能类似于0.3142849999999999,因此您会得到0.31428 结果。使用decimal 类型可以帮助解决这个问题

var value = 0.314285m;
var result = Math.Round(value, 5, MidpointRounding.AwayFromZero); //0.31429

【讨论】:

  • 非常感谢,是的,我尝试使用十进制类型并且它有效。
【解决方案2】:
public static double RoundUp(double i, int decimalPlaces)
{
    var power = Math.Pow(10, decimalPlaces);
    return Math.Ceiling(i * power) / power;
}


RoundDown(0.314285, 5); //0.31429

【讨论】:

    【解决方案3】:
    Math.Round(decimal number to round, int number of decimal places)
    

    我认为这应该适用于您正在尝试做的事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-15
      • 1970-01-01
      • 1970-01-01
      • 2019-07-02
      • 2022-12-12
      • 2013-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多