Here are a few ways to round a double in Java to the nearest integer, tenths, hundredths, or thousandths decimal place.

**UPDATE #1**: A reader commented that the code was not working for tenths, hundredths, and thousandths. It has been corrected, as suggested, by adding a decimal point to the multipliers and divisors.

**UPDATE #2**: A reader commented that the code was only working for positive numbers. It has been corrected to handle both positive and negative numbers (and zero, too).

Such simple code, yet two errors were identified by readers. Shame on me for not fully testing the code before posting. Feel free to let me know if you find any other scenarios that don’t work as expected.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 | double x = 0.0d; double y = 0.0d; // Double rounded to the nearest integer. y = (int) (x + ((x < 0.0) ? -0.5 : 0.5)); // Double rounded to the nearest tenth. y = ((int) ((x * 10.0) + ((x < 0.0) ? -0.5 : 0.5))) / 10.0; // Double rounded to the nearest hundredth. y = ((int) ((x * 100.0) + ((x < 0.0) ? -0.5 : 0.5))) / 100.0; // Double rounded to the nearest thousandth. y = ((int) ((x * 1000.0) + ((x < 0.0) ? -0.5 : 0.5))) / 1000.0; |

It worked for me with a minor modification. In order to work it properly all the divisors has to be doubles instead of integers. Adding a decimal point and a zero at the end of all these divisors (e.g., 10.0, 100.0, 1000.0) worked for me.

Thanks and keep up the good work!

This is incorrect. The int function will remove the floating point portion of the number which is not the same as the floor function, as the floor function will always round down to the next whole integer. While they will give the same result for positive numbers (int(2.7) = 2 and floor(2.7) = 2) they will give different results for negative numbers. int(-2.7) = -2, but floor(-2.7) = -3.

Both issues have been corrected. The floor function was not used as suggested, but the addition of either 0.5 or -0.5 is now included in a ternary operator to account for negative numbers.