java - 如何将 double 舍入到 n 长度(不是 n 小数位)?

标签 java double rounding

<分区>

我一直在努力寻找一种方法来确保双“值”的长度不大于 10。但是,由于我没有将其四舍五入到特定的小数位数,因此编程变得越来越困难。

例如,1234567.8912 和 12.345678912 都大于 10 位数字,但是,它们必须四舍五入到不同的小数位数。我的逻辑是找到小数点出现的位置并将 double 四舍五入为“10 - 小数点前的位数”。

我创建了两种不同的方法,但这两种方法似乎都无法正常工作。

    if ((Double.toString(value)).length()> 10){
        int counter = 0;
        double no_of_dec = 1;
        double no_of_int = 1;
        double new_value = 0;
        for (int i = 0; i< (Double.toString(value)).length(); i++){
            if ( (Character.toString((Double.toString(value)).charAt(i))).equals(".") ){
                counter = 1;
            } if (counter == 1){
                no_of_dec = no_of_dec * 10;
            } else if (counter == 0){
                no_of_int = no_of_int * 10;
            }
        } 
        no_of_dec = no_of_dec / (no_of_int);
        new_value = (double)Math.round(value * 100d/100d);
        return Double.toString(new_value);
    } else {
        return Double.toString(value);
    }


    if ((Double.toString(value)).length()> 10){
        double no_of_dec = 0;
        double no_of_int = 0;
        double new_value = 0;
        for (int i = 0; i< (Double.toString(value)).length(); i++){
            while (!(Character.toString((Double.toString(value)).charAt(i))).equals(".")){
                no_of_int = no_of_int + 1;
            }
        }
        no_of_dec = (Double.toString(value)).length() - no_of_int;
        no_of_dec = no_of_dec * 10;
        new_value = (double)Math.round(value * no_of_dec/no_of_dec);
        return Double.toString(new_value);
    } else {
        return Double.toString(value);
    }
}

最佳答案

我是这样做的:

private static BigDecimal getRounded(double n, int totalDigits) {

    String nString = Double.toString(n); // transform to string to make the job easier

    if(nString.contains(".")) {
        int dotPos = nString.indexOf("."); // = number of digits before the decimal point

        int remainingDigits = totalDigits - dotPos; // = remaining digits after the decimal point

        return new BigDecimal(nString).setScale(remainingDigits, BigDecimal.ROUND_HALF_UP); // round
    }

    return new BigDecimal(n);
}

这是我的测试:

double n = 1234567.8912;
System.out.println(getRounded(n, 10));

n = 12.345678915;
System.out.println(getRounded(n, 10));

结果是这样的:

1234567.891
12.34567892

演示:http://ideone.com/my7eB2

关于java - 如何将 double 舍入到 n 长度(不是 n 小数位)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40964902/

相关文章:

java - Storm 和 Spring 4 集成

c# - Visual Studio 如何在调试期间显示 System.Double?

java - 将字符串数组列表存储到双数组列表中?

Android - 自定义 SeekBar - 进度条上的圆角

octave - 四舍五入到小数点后两位

php - 四舍五入到最接近的分数(二分之一、四分之一等)

java - printf:NetBeans VS Eclipse

java - Libgdx 使scrollPane不需要点击交互来开始滚动

java - OpenGL - 为什么我的 fbo/纹理保持黑色?

c# - 获取下一个最小的 Double 数