How can I cast a Long to an int in Java? - java

Long x;
int y = (int) x;
Eclipse is marking this line with the error:
Can not cast Long to an int

Use primitive long
long x = 23L;
int y = (int) x;
You can't cast an Object (Long is an Object) to a primitive, the only exception being the corresponding primitive / wrapper type through auto (un) boxing
If you must convert a Long to an int, use Long.intValue():
Long x = 23L;
int y = x.intValue();
But beware: you may be losing information! A Long / long has 64 bit and can hold much more data than an Integer / int (32 bit only)

Long x is an object.
int y = x.intValue();

int y = (int) (long) x;
is working.

Long x1 = 123L;
long x2 = 123L;
int y1 = Math.toIntExact(x1);
int y2 = Math.toIntExact(x2);
This conversion will work with primitive as well as with non-primitive types as well.

Related

Convert/Cast Double to int? (Object to primitive type)

How do I convert/cast a Double object to an int?
Double d = new Double(12.34);
int i = 12 //is what I'm looking for
If I had a double I would just use:
double z = 12.34;
int i = (int)z;
Note: I want it to truncate the Double (so 12.9 becomes 12) because I know that d actually was an integer that was converted to a Double.
I.e. I want to call (int) on a Double.
To perform this operation you need to call the intValue method on the Double object:
int i = d.intValue();
This method performs a cast, into an int value, on the double value wrapped within the Double object, d.
Note that it does not check for null before attempting this.
If you want to use a cast you can use
Double d = 12.34;
int i = (int) (double) d;
You can't cast from Double to int in one step.

How to covert a double to an int

I'm trying to convert a double to an int but I don't get my expected results. Can someone help me?
Here's my code. My expected output is 21 but I keep getting 21.0.
double costItem2 = 32.55;
int budget2 = 713;
double totalItem2 = budget2 / costItem2;
totalItem2 = (int) totalItem2;
System.out.println(totalItem2);
Thats because double totalItem2 still holds a double even if you cast the result that you're assigning it to an int
You have to:
int totalItemTemp2 = (int) totalItem2
Your best option is to format the output yourself. Here is how:
NumberFormat numFormat = new DecimalFormat("#.####"); // you can have it as #.## if you only want up to two decimal places
double costItem2 = 32.55;
int budget2 = 713;
double totalItem2 = budget2 / costItem2;
System.out.println(numFormat.format(totalItem2));
so for example, 123.00 would be printed as 123
casting totalItem2 to int will not change the type of totalItem2(which will still remain a double).
int tmpInt = (int) totalItem2;
System.out.println(tmpInt);
should fix it.
You can't change the type of totalItem2 at runtime like this,
double totalItem2 = budget2 / costItem2; // <-- totalItem2 is a double, not int
totalItem2 = (int) totalItem2; // <-- truncates
But you could change the declaration to an int with a cast like,
int totalItem2 = (int) (budget2 / costItem2); // <-- truncates
or a long with out,
long totalItem2 = Math.round(budget2 / costItem2); // <-- rounds, no cast!
or an int bu using a float costItem2,
float costItem2 = 32.55f;
int totalItem2 = Math.round(budget2 / costItem2); // <-- rounds, no cast!

convert double into int

I have following double value:
8.943 need to convert(cast) into int e.g: 8.943*1000000 = 8943000
required value --> 8943000
please help!
thanks.
double myDouble = 8.943
int myInt = (int) (myDouble * 1000000)
Using (int) casts the double into an int

Convert double to Int, rounded down

How to convert a double value to int doing the following:
Double If x = 4.97542. Convert to int x = 4.
Double If x = 4.23544. Convert to int x = 4.
That is, the answer is always rounding down.
If you explicitly cast double to int, the decimal part will be truncated. For example:
int x = (int) 4.97542; //gives 4 only
int x = (int) 4.23544; //gives 4 only
Moreover, you may also use Math.floor() method to round values in case you want double value in return.
If the double is a Double with capital D (a boxed primitive value):
Double d = 4.97542;
int i = (int) d.doubleValue();
// or directly:
int i2 = d.intValue();
If the double is already a primitive double, then you simply cast it:
double d = 4.97542;
int i = (int) d;
double myDouble = 420.5;
//Type cast double to int
int i = (int)myDouble;
System.out.println(i);
The double value is 420.5 and the application prints out the integer value of 420
Another option either using Double or double is use Double.valueOf(double d).intValue();. Simple and clean
I think I had a better output, especially for a double datatype sorting.
Though this question has been marked answered, perhaps this will help someone else;
Arrays.sort(newTag, new Comparator<String[]>() {
#Override
public int compare(final String[] entry1, final String[] entry2) {
final Integer time1 = (int)Integer.valueOf((int) Double.parseDouble(entry1[2]));
final Integer time2 = (int)Integer.valueOf((int) Double.parseDouble(entry2[2]));
return time1.compareTo(time2);
}
});

Long Division in Java not working as expected

class LongDiv{
public static void main(String [] args){
final long x = 24*60*60*1000*1000;
final long y = 24*60*60*1000;
System.out.println(x/y);
}
}
although the expected answer is 1000, but the javac gives it as 5. Reason?
The long x you are creating isn't the value you expected. It is in the integer range. To create longs, use:
final long x = 24L*60L*60L*1000L*1000L;
final long y = 24L*60L*60L*1000L;
System.out.println(x/y);
The x you computed, in the integer range, was 500654080. This divided by the y ( = 86400000), results in 5.794607407407407.... Java truncates the decimal part which causes the 5.
By adding an L after the number literal, you tell the compiler to compile it as a long instead of an int. The value for x you expected is 86400000000. But is was compiled as an int.
We can reproduce the wrong value for x (500654080) by truncating it to an int:
// First correct
long x = 24L*60L*60L*1000L*1000L;
/* x = `86400000000`; */
// Now truncate
x &= 0xFFFFFFFFL; // again: don't forget the L suffix
/* x = `500654080` */
The expressions 24*60*60*1000*1000 is an int type not a long What you want is 24L*60*60*1000*1000 which is long
This is what you have.
final long x = (24*60*60*1000*1000) & 0xFFFFFFFF;
final long y = (24*60*60*1000) & 0xFFFFFFFF;
System.out.println(x/y);
what you want is
final long x = 24L*60*60*1000*1000;
final long y = 24L*60*60*1000;
System.out.println(x/y);
casting (forcing) to long works in case of literal values for the right operand; but the problem persists in case of assigning one long variable to another, as in the below given example:
package utils;
public class Utils {
public static void main(String ... clps){
Utils.longDivision();
Utils.doubleDivision();
}
private static void doubleDivision(){
double x=new Long("54321").doubleValue();
double y=new Long("12345").doubleValue();
double difference=x - y;
double percentage=(difference/x)*100.00;
System.out.println("\nDouble Division ==> X : "+x+" ; Y : "+y+" ; Difference : "+difference+" ; percentage : "+percentage+"\n");
}
private static void longDivision(){
long x=new Long("54321").longValue();
long y=new Long("12345").longValue();
long difference=x - y;
long percentage=(difference/x)*100L;
System.out.println("\nLong Division ==> X : "+x+" ; Y : "+y+" ; Difference : "+difference+" ; percentage : "+percentage+"\n");
}
}
The only way i could get proper answer is by converting the division of longs into division of doubles. It is very strange why division of longs behaves in such mysterious manner.
longDivision gives the answer as zero whereas the doubleDivision gives the correct answer.
I hope this helps others who encountered similar issues...
24*60*60*1000*1000 is too large to fit into an int and overflows.
Tricky one!
The issue is that 24, 60, and 1000 are Java literal ints. Before the values are assigned to x and y, they are truncated to fit in int values. Try
System.out.print(x + ", " + y);
to see exactly what I mean. The quick fix is to make your literals into long values like so:
public class LongDiv{
public static void main(String [] args){
final long x = 24l*60l*60l*1000l*1000l;
final long y = 24l*60l*60l*1000l;
System.out.println(x/y);
}
}

Categories

Resources