How can I convert a long to int in Java?
In Spring, there is a rigorous way to convert a long to int
not only lnog can convert into int,any type of class extends Number can convert to other Number type in general,here I will show you how to convert a long to int,other type vice versa.
Long l = 1234567L;
int i = org.springframework.util.NumberUtils.convertNumberToTargetClass(l, Integer.class);
Long l = 100;
int i = Math.round(l);
If you want to make a safe conversion and enjoy the use of Java8 with Lambda expression You can use it like:
val -> Optional.ofNullable(val).map(Long::intValue).orElse(null)
For small values, casting is enough:
long l = 42;
int i = (int) l;
However, a long
can hold more information than an int
, so it's not possible to perfectly convert from long
to int
, in the general case. If the long
holds a number less than or equal to Integer.MAX_VALUE
you can convert it by casting without losing any information.
For example, the following sample code:
System.out.println( "largest long is " + Long.MAX_VALUE );
System.out.println( "largest int is " + Integer.MAX_VALUE );
long x = (long)Integer.MAX_VALUE;
x++;
System.out.println("long x=" + x);
int y = (int) x;
System.out.println("int y=" + y);
produces the following output on my machine:
largest long is 9223372036854775807
largest int is 2147483647
long x=2147483648
int y=-2147483648
Notice the negative sign on y
. Because x
held a value one larger than Integer.MAX_VALUE
, int y
was unable to hold it. In this case, it wrapped around to the negative numbers.
If you wanted to handle this case yourself, you might do something like:
if ( x > (long)Integer.MAX_VALUE ) {
// x is too big to convert, throw an exception or something useful
}
else {
y = (int)x;
}
All of this assumes positive numbers. For negative numbers, use MIN_VALUE
instead of MAX_VALUE
.
long x = 3120L; //take any long value int z = x.intValue(); //you can convert double to int also in the same way
if you needto covert directly then
longvalue.intvalue();
In Java, a long is a signed 64 bits number, which means you can store numbers between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807 (inclusive).
A int, on the other hand, is signed 32 bits number, which means you can store number between -2,147,483,648 and 2,147,483,647 (inclusive).
So if your long is outside of the values permitted for an int, you will not get a valuable conversion.
Details about sizes of primitive Java types here:
http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html