This question already has an answer here:
-
How to cast a double to an int in Java by rounding it down?
9 answers
Quick question, What is the best way to convert an primitive data type double to a primitive data type int. Currently I am using the following code but it seems to be a lot of methods to do a simple task.
double i = 2.0;
int i2 = Integer.parseInt(Double.toString(i));
just cast double to (int)
double i = 2.0;
int i2 = (int) i;
You could either cast the double to an int:
double i = 2.0
int i2 = (int) i;
or, you could round the number to the nearest whole number, then cast it to an int, just in case you would like to round:
double i = 2.2
int i2 = (int) Math.round(i);
or, you could use
double i = 2.0
int i2 = Integer.parseInt(String.valueOf(i));
About best, though, the first option would be best for the least code, and the second would be better if you would like to get the closest integer to the double.
You can turn any object from one compatible type to another by using 'type-casting'. You use this syntax:
double i = 2.0;
int i2 = (int) i;
Notice how I just put (int)
before the variable i
? This basically says 'hey, try to make i an int, if you can'. Since java can easily convert a float to an int, it will.
Also you can use Math.floor()
.
public class Example {
public static void main(String args[]) {
double i = 2.9;
System.out.println((int)(i));
System.out.println((int)Math.floor(i));
System.out.println((int)(-i));
System.out.println((int)Math.floor(-i));
}
}
output:
2
2
-2
-3