How can I convert a long to int in Java?
You can cast a long to int so long as the number is less than 2147483647 without an error.
Using Math.Math. round() accepts a double value and converts it into the nearest long value by adding 0.5 to the value and truncating its decimal points. The long value can then be converted to an int using typecasting.
Updated, in Java 8:
Math.toIntExact(value);
Original Answer:
Simple type casting should do it:
long l = 100000; int i = (int) l;
Note, however, that large numbers (usually larger than 2147483647
and smaller than -2147483648
) will lose some of the bits and would be represented incorrectly.
For instance, 2147483648
would be represented as -2147483648
.
Long x = 100L; int y = x.intValue();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With