136

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?

Sean Bright
  • 118,630
  • 17
  • 138
  • 146
David
  • 14,569
  • 34
  • 78
  • 107
  • possible duplicate of http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java – Matt Ball Apr 16 '10 at 17:09
  • 6
    You should really elaborate "not working" in more detail. What happens? What happens not? What did you expect? What errors did you got? Do you have a `round()` method in the same class? Did you `import static java.lang.Math.*`? Etc.. There are a lot of ways to round numbers and thus also a lot of possible answers. In other words, your question is vague and ambiguous and can't be reasonably answered in its current form. It's shooting in the dark. – BalusC Apr 16 '10 at 17:09
  • 1
    Does "not working" mean not rounding to nearest int, or throwing exception, or not rounding up/down? This question is useless without having to cross-reference the context with the answer. – modulitos Jul 11 '14 at 21:25

8 Answers8

270

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);
Drupad Panchal
  • 383
  • 3
  • 10
Mihir Mathuria
  • 6,479
  • 1
  • 22
  • 15
  • 5
    Consider using Math.toIntExact(long) instead of just casting to an int; a double can hold quite a range of values and you probably don't want to silently throw out the most significant bits if your double is larger than you expect. – othp Mar 01 '18 at 16:38
  • I believe the cast is not necessary. I'm not aware if it was in the past, but round does return int. – Dropout May 18 '18 at 09:22
  • @Dropout Math.round returns an int if you give it a float, and a long if you give it a double. – Tur1ng Jul 03 '18 at 15:47
31

If you don't like Math.round() you can use this simple approach as well:

int a = (int) (doubleVar + 0.5);
  • 7
    There is clearly no valuable reason for not liking `Math.round()`: http://stackoverflow.com/a/6468757/1715716 – Gauthier Boaglio Feb 09 '16 at 22:02
  • 5
    This solution is shorter, does not need an import and is portable to many other programming languages with minimal changes. And it might even be faster depending on your platform: https://stackoverflow.com/questions/12091014/what-is-the-most-efficient-way-to-round-a-float-value-to-the-nearest-integer-in/12091343#12091343 – Dr. Daniel Thommes Feb 11 '16 at 13:50
  • 2
    I'm not criticizing your answer, which I find **very useful** for the reason you mention. I was, by this comment, addressing people who would be afraid to use `Math.round()`, which does "literally" the same as the solution you provide, that is all. Cheers. – Gauthier Boaglio Feb 11 '16 at 16:37
  • 3
    Yep, like nehz said, I believe this would round -2.1 to -1, for example. – Ben Aaronson Jul 20 '16 at 15:23
  • This approach is incorrect. `Math.round(doublevar)` will perform rounding on the double number, basically returning the closest integer to the specified double. On the contrary, `(int) doublevar` will just remove the decimal portion of the double, potentially yielding a different result. As an example, `Math.round(5.7)` will return 6, but `(int) 5.7` returns 5. – Alberto Hormazabal Oct 28 '16 at 14:26
  • 7
    @AlbertoHormazabal, didn't you notice that he added `0.5`? – Sasha Nov 20 '16 at 03:48
  • 1
    I wonder why during the last 6 years nobody wrote that this replacement for `Math.round()` gives wrong results for negative input numbers. Ok here it is: Do not replace! – Hartmut Pfitzinger Jan 12 '21 at 14:01
12

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.

valerybodak
  • 4,195
  • 2
  • 42
  • 53
  • I agree with the anivaler's answer. But if you need to just round off to highest integer number, you can you like below: double decimalNumber = 4.56777; System.out.println( new Float( Math.round(decimalNumber )) ); Output : 5 – Smeet Nov 19 '15 at 11:01
9

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.

Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66
Divyansh Rai
  • 190
  • 1
  • 5
3
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();
  }
}
Scott
  • 4,066
  • 10
  • 38
  • 54
1

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.

CubeJockey
  • 2,209
  • 8
  • 24
  • 31
thug-gamer
  • 355
  • 6
  • 9
  • 4
    There are 2 Math.round methods. The one which takes a float returns an integer, that is correct. But the one that takes a double returns a long. – Dominik Ehrenberg Apr 24 '15 at 21:19
1
public static int round(double d) {
    if (d > 0) {
        return (int) (d + 0.5);
    } else {
        return (int) (d - 0.5);
    }
}
Alexander Cyberman
  • 2,114
  • 3
  • 20
  • 21
-1

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.

MarchingHome
  • 1,184
  • 9
  • 15
Joey Gibson
  • 7,104
  • 1
  • 20
  • 14