Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round a double in Java

I have found this great solution for rounding:

static Double round(Double d, int precise) {     BigDecimal bigDecimal = new BigDecimal(d);     bigDecimal = bigDecimal.setScale(precise, RoundingMode.HALF_UP);     return bigDecimal.doubleValue(); } 

However, the results are confusing:

System.out.println(round(2.655d,2)); // -> 2.65 System.out.println(round(1.655d,2)); // -> 1.66 

Why is it giving this output? I'm using jre 1.7.0_45.

like image 844
pushistic Avatar asked Feb 26 '14 09:02

pushistic


People also ask

How do you round a double in Java?

Using Math. Math. round() accepts a double value and converts it into the nearest long value by adding 0.5 to the value and truncating its decimal points.

How do you trim a double in Java?

Shift the decimal of the given value to the given decimal point by multiplying 10^n. Take the floor of the number and divide the number by 10^n. The final value is the truncated value.

How do you round a double to 3 decimal places in Java?

In this approach, we first Multiply the number by 10n using the pow() function of the Math class. Then the number is rounded to the nearest integer. At last, we divide the number by 10n. By doing this, we get the decimal number up to n decimal places.


1 Answers

You have to replace

BigDecimal bigDecimal = new BigDecimal(d); 

with

BigDecimal bigDecimal = BigDecimal.valueOf(d); 

and you will get the expected results:

2.66 1.66 

Explanation from Java API:

BigDecimal.valueOf(double val) - uses the double's canonical string representation provided by the Double.toString() method. This is preferred way to convert a double (or float) into a BigDecimal.

new BigDecimal(double val) - uses the exact decimal representation of the double's binary floating-point value and thus results of this constructor can be somewhat unpredictable.

like image 191
Boris Avatar answered Sep 17 '22 13:09

Boris