java - 我的方法无法舍入1,66666 (5.0/3)

标签 java floating-point rounding

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

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

最佳答案

假设您想要进行标准舍入(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
}

关于java - 我的方法无法舍入1,66666 (5.0/3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37255280/

相关文章:

Angular 2 - 如何轮计算数字?

c++ - 等式中不考虑小数

algorithm - 你能帮我确定这个应用程序的四舍五入吗?

java - 重新运行 Spring Boot 配置注释处理器以更新生成的元数据

java - 在 JTable 中搜索

java - 不同的舍入方法似乎不起作用

c - C 中的脚本未正确添加 float

java - 如何知道浮点值是否大于Integer.MAX_VALUE?

javascript - Spring Boot 应用程序 JS 和 CSS 未在独立服务器中绑定(bind)(Apache Tomcat 版本 9.0)

java - 这是一个有效的十六进制值吗?