Rounding to Two Decimal Places in Java
Many developers encounter challenges when attempting to round floating-point numbers to specific decimal places in Java. This is particularly true when the desired output must remain a double.
One common approach involves utilizing Math.round(), as demonstrated in the following code:
class Round { public static void main(String[] args) { double a = 123.13698; double roundOff = Math.round(a * 100) / 100; System.out.println(roundOff); } }
However, this approach often fails to produce the desired result. Instead of rounding to 123.14, it outputs 123.
To rectify this issue, a slight modification to line 4 is required:
double roundOff = Math.round(a * 100.0) / 100.0;
By adding .0 to the multiplication factor, the result is cast to a double with two decimal places. This ensures that the final result also has two decimal places.
Alternatively, as suggested by @Rufein, one can cast the rounded value to a double:
double roundOff = (double) Math.round(a * 100) / 100;
This approach also effectively produces the desired output of 123.14 with two decimal places.
The above is the detailed content of How to Correctly Round Doubles to Two Decimal Places in Java?. For more information, please follow other related articles on the PHP Chinese website!