How to Convert double to int in Java

In this post we’ll see how to convert double to int in Java.

Considerations while converting double to int in Java

While converting double to int two things you need to consider are-

  1. Range of double is much more than the int, if the double you are trying to convert to int is out of range for int then how to handle that.
  2. In double value there are fractional parts where as int doesn’t have fractional part so what to do with fractional part is another thing to consider. Fractional part can be truncated or you need to round the double value to the nearest integer.

Converting using intValue() method or by type casting

You can convert double to int using intValue() method of the Double class (needs a Double object) or by explicitly type casting double value to int. In fact intValue() method implementation also do the type casting and returns the value of this Double as an int after a narrowing primitive conversion. Problem with these two methods is that the rounding to the nearest integer doesn’t happen while converting double to int, fractional part is truncated.
Converting double to int using intValue() method

Output

Couple of things to note here- double value is truncated while converting it to int and this way of conversion needs an instance of Double class.

Converting double to int using explicit casting

Output

Converting double to int with rounding to nearest integer

Though the above two ways convert double to int but truncate the fractional part rather than rounding the double to the nearest integer which is not what you’d want in most of the scenarios. In order to do the rounding you have to use Math.round(double d) method which returns the closest long to the passed argument.
Since the returned value is long so further casting is required to convert the long value to int.

Math.round() method also takes care of the special cases-

  • If the argument is NaN, the result is 0.
  • If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE.
  • If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE.

Converting double to int using Math.round()

Output

As you can see here rounding is done to the nearest integer. Since the returned value from the method Math.round(double d) is long so casting to int is also required.

Example with different double arguments

Output

That’s all for the topic How to Convert double to int in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.