Rounding a double to turn it into an int (java)
Right now I'm trying this:
int a = round(n);
where n
is a double
but it's not working. What am I doing wrong?
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);
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.
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.
import java.math.*;
public class TestRound11 {
public static void main(String args[]){
double d = 3.1537;
BigDecimal bd = new BigDecimal(d);
bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP);
// output is 3.15
System.out.println(d + " : " + round(d, 2));
// output is 3.154
System.out.println(d + " : " + round(d, 3));
}
public static double round(double d, int decimalPlace){
// see the Javadoc about why we use a String in the constructor
// http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html#BigDecimal(double)
BigDecimal bd = new BigDecimal(Double.toString(d));
bd = bd.setScale(decimalPlace,BigDecimal.ROUND_HALF_UP);
return bd.doubleValue();
}
}