Explain Codes LogoExplain Codes Logo

Converting double to integer in Java

java
floating-point-arithmetic
precision
edge-cases
Nikita BarsukovbyNikita Barsukov·Dec 6, 2024
TLDR

To convert a double to an int in Java, simply perform a cast. Wrap the double in (int):

// Like a cookie jar, it takes the 9 and leaves the .7 behind int myInt = (int) 9.7; // Results in 9

If rounding is necessary, use Math.round before casting:

// Kindly teacher style, 0.5 or higher it rounds up int myInt = (int) Math.round(9.7); // Results in 10

When you want to make sure a double is rounded to the nearest whole number before turning it into an int, use Math.round(). This will prevent any unwanted truncation:

// No decimal left behind! double myDouble = 9.7; long rounded = Math.round(myDouble); // Rounds to nearest whole number int myInt = (int) rounded; // Civilized conversion from long to int

You can also convert a Double object to an int directly using its built-in .intValue() method:

// I used to be a double, but then I took an int arrow to the knee Double doubleObject = 9.7; int myInt = doubleObject.intValue(); // Outputs 9

Integral know-how: Rounding, truncation, casting

Fun-house of rounding

Choosing the correct rounding strategy can make a huge difference. Java provides several methods for different types of rounding:

  • Math.round(): This applies traditional rounding rules. Halfway values round up.

  • Math.ceil(): Heavenly rounding. Your double will always round up.

  • Math.floor(): Grounded rounding. Your double will always round down.

Double Trouble

Casting a double to an int is not always straightforward. When the double value is out of range for an int, you can get unpredictable results. Proceed with caution for values near Integer.MAX_VALUE or Integer.MIN_VALUE.

Special Cases bonanza

Java has rules for special cases such as NaN (Not-a-Number) or infinity:

  • NaN turned into an int spells: 0!
  • Positive infinity transformed to int summons the Integer.MAX_VALUE.
  • Negative infinity begets the Integer.MIN_VALUE.

Converting double to int: Industry best practices

The Importance of Precision

Precision is mission critical in industries like finance. Consider alternatives like BigDecimal for added control over precision and rounding, to safeguard against errors from floating-point arithmetic.

Case by Case Conversion

In enterprise environments, remember to validate data inputs and handle edge cases. Understand the data flow and consider the precision needs of the task at hand.