编程语言
首页 > 编程语言> > java-如何四舍五入到n个长度(不是n个小数位)?

java-如何四舍五入到n个长度(不是n个小数位)?

作者:互联网

这个问题已经在这里有了答案:            >            How to round a number to n decimal places in Java                                    29个
我一直试图找到一种方法来确保双精度“值”的长度不大于10.但是,由于我没有将其四舍五入到小数点后的位数,因此编程变得越来越困难.

例如,1234567.8912和12.345678912都大于10位,但是必须将它们四舍五入为不同的小数位数.我的逻辑是找到小数点在哪里,并将双精度数四舍五入为“ 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

标签:rounding,double,java
来源: https://codeday.me/bug/20191112/2023747.html