【问题标题】:My method cant round 1,66666 (5.0 / 3) [duplicate]我的方法无法绕过 1,66666(5.0 / 3)[重复]
【发布时间】:2016-05-16 13:37:13
【问题描述】:
public static double round(double number,int numberofdecimals){
    int n=1;
    for (int i = 1; i <= numberofdecimals;i++){
        n=n*10;
    }


    double  c =((number - Math.floor(number))*n);
    c= Math.floor(c);

    return (Math.floor(number) + (c/n));
}

我的方法完美地舍入了一些双精度,但是当我将 ((5.0 / 3) ,2) 放入我的数字参数时,它给了我 1.6600000 发生了什么?

【问题讨论】:

  • 这仅仅是因为浮点数学被破坏了。看到这个 - stackoverflow.com/questions/588004/…
  • 我编辑了方法 broj 是数字,但在我的语言中我忘记将其翻译成英文,但这不是问题
  • 看起来问题只是由于在计算过程中丢失了精度。请参阅this post 了解更多信息。
  • Milos,请查看@Blue 发布的问题,看看它是否有足够的信息来帮助您解决问题。 (提示:应该)。
  • 不确定您还能期待什么其他结果,因为您明确使用了floor

标签: java floating-point rounding


【解决方案1】:

假设您要进行标准舍入(1.5 舍入到 2.0;1.49 舍入到 1.0)然后尝试以下操作:

public static double round(double number,int numberofdecimals){
    int n=1;
    for (int i = 1; i <= numberofdecimals;i++){
        n=n*10;
    }

    double  c =((number - Math.floor(number))*n); // Here c = 66.6666666...
    c= Math.floor(c + 0.5); // Now c is 67.0.

    return (Math.floor(number) + (c/n)); // returns 1.67
}

【讨论】:

  • 为了我的目的,这解决了问题,非常感谢老兄。
猜你喜欢
  • 2015-10-28
  • 1970-01-01
  • 2015-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多