Cast Double to Integer in Java

Converting double to integer in Java

is there a possibility that casting a double created via Math.round() will still result in a truncated down number

No, round() will always round your double to the correct value, and then, it will be cast to an long which will truncate any decimal places. But after rounding, there will not be any fractional parts remaining.

Here are the docs from Math.round(double):

Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression:

(long)Math.floor(a + 0.5d)

Cast Double to Integer in Java

A Double is not an Integer, so the cast won't work. Note the difference between the Double class and the double primitive. Also note that a Double is a Number, so it has the method intValue, which you can use to get the value as a primitive int.

How do I cast a double to an int in Java?

double is not an object, it is a primitive type.

Simply writing (int)b will do the job.

If you really need a Double object, you need to construct one.

How to cast a double to an int in Java by rounding it down?

Casting to an int implicitly drops any decimal. No need to call Math.floor() (assuming positive numbers)

Simply typecast with (int), e.g.:

System.out.println((int)(99.9999)); // Prints 99

This being said, it does have a different behavior from Math.floor which rounds towards negative infinity (@Chris Wong)

How to convert Double to int directly?

If you really should use Double instead of double you even can get the int Value of Double by calling:

Double d = new Double(1.23);
int i = d.intValue();

Else its already described by Peter Lawreys answer.

Casting Double to Integer

You cannot cast directly from Double to Integer. You need to do the following:

Double d = new Double(1.23);
int i = d.intValue();

as suggested in How to convert Double to int directly?

Java: Casting double to int Integer.MAX_VALUE

In the expression:

double randomDouble = Integer.MAX_VALUE + rand.nextInt((max - min) + 1);

the right hand side of the expression will first assign the sum to an integer, then this result will be cast to a double. Since adding anything to Integer.MAX_VALUE will result in overflow, you end up with a negative number, because the sign bit gets flipped as part of the overflow.

If you want a double, then just cast MAX_VALUE to double:

double randomDouble = (double)Integer.MAX_VALUE + (double)rand.nextInt((max - min) + 1);

Now in this case you get what you want, because you are adding a random number to a double, which is bearing the largest int value, which is not near the limit for what doubles can store.

Demo



Related Topics



Leave a reply



Submit