Round Double To Nearest Hundredth

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.

3 thoughts on “Round Double To Nearest Hundredth”

  1. 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!

  2. 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.

  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.

Leave a Comment