Is Math.round() always reliable for double-to-int conversion in Java?

Both the above solutions above are great, but what if you need something different? Sometimes, you don’t want rounding—you want control. That’s when Math.floor() and Math.ceil() are useful.

Imagine you’re dealing with convert double to int java, but instead of rounding normally, you need to always round down (e.g., currency conversions) or always round up (e.g., setting a minimum value).

:pushpin: Real-world analogy:

  • Math.floor() → Always round down, like a discount rounding to the nearest dollar.
  • Math.ceil() → Always round up, like setting a minimum price.

:small_blue_diamond: Example (Always Round Down):

public class ConvertDoubleToInt {
    public static void main(String[] args) {
        double x = 1.9999999998;
        int y = (int) Math.floor(x);  // y = 1
        System.out.println(y);
    }
}

:small_blue_diamond: Example (Always Round Up):

public class ConvertDoubleToInt {
    public static void main(String[] args) {
        double x = 1.2;
        int y = (int) Math.ceil(x);  // y = 2
        System.out.println(y);
    }
}

:pushpin: When to use Math.floor() or Math.ceil()?

:heavy_check_mark: Use Math.floor() if you want to always round down.

:heavy_check_mark: Use Math.ceil() if you want to always round up.

:warning: Avoid if:

If standard rounding is what you need, Math.round() is still the best choice.