Explain Codes LogoExplain Codes Logo

Cast Double to Integer in Java

java
null-check
rounding-strategy
explicit-cast
Anton ShumikhinbyAnton Shumikhin·Dec 29, 2024
TLDR

For a swift cast from Double to Integer, use intValue() to truncate any decimal points, or, round your Double with (int)Math.round():

Double dbValue = 3.14; Integer intTruncated = dbValue.intValue(); // The decimal point: "I don't always disappear but when I do, it's because of truncation." Integer intRounded = (int) Math.round(dbValue); // 3.14: "I feel a round up coming..."

Beware of precision loss and invasive NullPointerException.

Null and non-compliant values

Before attempting to cast, do a null-check for NullPointerException prevention. When faced with non-friendly values such as Infinity or NaN, bear in mind that intValue() and (int) might not convert as expected. Use isInfinite() or isNaN() for these scenarios.

Double dbValue = Double.NaN; if(dbValue == null || dbValue.isInfinite() || dbValue.isNaN()) { throw new IllegalArgumentException("Sorry, you're not my type. -Double, probably"); }

When the decimal matters

For projects like financial applications, meter readings, or culinary measurements where precision is key, the rounding strategy becomes absolutely crucial. With procedures such as Math.ceil() or Math.floor(), a better approximation can be drawn as opposed to regular truncation.

// Ceiling is just your "upper rounded" Integer intCeil = (int) Math.ceil(dbValue); // Floor: because sometimes, we all get a little down (rounded) Integer intFloor = (int) Math.floor(dbValue);

Phases of conversion

Related to Double to Integer, explicit cast (int) and Double's our golden boy intValue() both truncate but with distinct styles. The former is abrupt and the latter, cautious to avoid ClassCastException. As for Integer, it's a team play with Integer.valueOf() and intValue():

Integer integerValue = Integer.valueOf(dbValue.intValue()); // Tag, you're now an Integer!

Edge cases

An attempt to directly cast from Double to Integer will fail due to type differences. Stick with the conversion methods listed above and maintain vigilance when numbers are close to Integer.MAX_VALUE or Integer.MIN_VALUE to bypass any unintended drama.

Deep diving: getting granular

Overflow and Underflow: Be especially careful when casting doubles with large magnitude; keep your values within int's play zone (-2³¹ to 2³¹-1).

Financial calculations: Round off with BigDecimal class - it's the CFO of currency calculations.

Double Object vs double Primitive: A Double can be null while a double cannot, it gets lonely sometimes.

Rounding techniques: Explore DecimalFormat or BigDecimal for custom rounding means and ends.

Pro tips

  • Check for null and special outfits (NaN, infinities) before casting.
  • Choose your rounding weapon wisely; it's not always the quickest draw that wins.
  • Playing pass-the-parcel with Double and Integer? Use intValue() to avoid a party foul.