Rounding a double to turn it into an int (java)
What is the return type of the round()
method in the snippet?
If this is the Math.round()
method, it returns a Long when the input param is Double.
So, you will have to cast the return value:
int a = (int) Math.round(doubleVar);
If you don't like Math.round() you can use this simple approach as well:
int a = (int) (doubleVar + 0.5);
The Math.round function is overloaded When it receives a float value, it will give you an int. For example this would work.
int a=Math.round(1.7f);
When it receives a double value, it will give you a long, therefore you have to typecast it to int.
int a=(int)Math.round(1.7);
This is done to prevent loss of precision. Your double value is 64bit, but then your int variable can only store 32bit so it just converts it to long, which is 64bit but you can typecast it to 32bit as explained above.
Rounding double to the "nearest" integer like this:
1.4 -> 1
1.6 -> 2
-2.1 -> -2
-1.3 -> -1
-1.5 -> -2
private int round(double d){
double dAbs = Math.abs(d);
int i = (int) dAbs;
double result = dAbs - (double) i;
if(result<0.5){
return d<0 ? -i : i;
}else{
return d<0 ? -(i+1) : i+1;
}
}
You can change condition (result<0.5) as you prefer.