Reputation: 14953
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?
Upvotes: 138
Views: 332119
Reputation: 190
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.
Upvotes: 9
Reputation: 2168
public static int round(double d) {
if (d > 0) {
return (int) (d + 0.5);
} else {
return (int) (d - 0.5);
}
}
Upvotes: 2
Reputation: 355
Documentation of Math.round
says:
Returns the result of rounding the argument to an integer. The result is equivalent to
(int) Math.floor(f+0.5)
.
No need to cast to int
. Maybe it was changed from the past.
Upvotes: 1
Reputation: 697
If you don't like Math.round() you can use this simple approach as well:
int a = (int) (doubleVar + 0.5);
Upvotes: 30
Reputation: 7104
You really need to post a more complete example, so we can see what you're trying to do. From what you have posted, here's what I can see. First, there is no built-in round()
method. You need to either call Math.round(n)
, or statically import Math.round
, and then call it like you have.
Upvotes: -1
Reputation: 6539
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);
Upvotes: 276
Reputation: 4413
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.
Upvotes: 12
Reputation: 4200
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();
}
}
Upvotes: 3