Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a long to int in Java?

Tags:

java

How can I convert a long to int in Java?

like image 371
Arthur Avatar asked Dec 04 '10 19:12

Arthur


People also ask

Can you cast from long to int?

You can cast a long to int so long as the number is less than 2147483647 without an error.

How do you convert long double to int?

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.


2 Answers

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.

like image 166
Frxstrem Avatar answered Oct 23 '22 11:10

Frxstrem


Long x = 100L; int y = x.intValue(); 

like image 20
Laxman Avatar answered Oct 23 '22 09:10

Laxman