Double value to round up in Java

后端 未结 10 1902
我寻月下人不归
我寻月下人不归 2020-12-07 12:44

I have a double value = 1.068879335 i want to round it up with only two decimal values like 1.07.

I tried like this

DecimalFormat df=new         


        
10条回答
  •  -上瘾入骨i
    2020-12-07 13:11

    If you do not want to use DecimalFormat (e.g. due to its efficiency) and you want a general solution, you could also try this method that uses scaled rounding:

    public static double roundToDigits(double value, int digitCount) {
        if (digitCount < 0)
            throw new IllegalArgumentException("Digit count must be positive for rounding!");
    
        double factor = Math.pow(10, digitCount);
        return (double)(Math.round(value * factor)) / factor;
    }
    

提交回复
热议问题