Rounding a double to turn it into an int (java)

283,869

Solution 1

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);

Solution 2

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

int a = (int) (doubleVar + 0.5);

Solution 3

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.

Solution 4

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.

Solution 5

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();
  }
}
Share:
283,869
David
Author by

David

I'm David.

Updated on February 04, 2020

Comments

  • David
    David about 4 years

    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?

  • Dominik Ehrenberg
    Dominik Ehrenberg about 9 years
    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.
  • Smeet
    Smeet over 8 years
    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
  • Gauthier Boaglio
    Gauthier Boaglio about 8 years
    There is clearly no valuable reason for not liking Math.round(): stackoverflow.com/a/6468757/1715716
  • Dr. Daniel Thommes
    Dr. Daniel Thommes about 8 years
    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: stackoverflow.com/questions/12091014/…
  • Gauthier Boaglio
    Gauthier Boaglio about 8 years
    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.
  • Ben Aaronson
    Ben Aaronson almost 8 years
    Yep, like nehz said, I believe this would round -2.1 to -1, for example.
  • Alberto Hormazabal
    Alberto Hormazabal over 7 years
    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.
  • Sasha
    Sasha over 7 years
    @AlbertoHormazabal, didn't you notice that he added 0.5?
  • Danon
    Danon about 7 years
    There are no global functions in java, for a start.
  • othp
    othp about 6 years
    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.
  • Dropout
    Dropout almost 6 years
    I believe the cast is not necessary. I'm not aware if it was in the past, but round does return int.
  • Tur1ng
    Tur1ng almost 6 years
    @Dropout Math.round returns an int if you give it a float, and a long if you give it a double.
  • Hartmut Pfitzinger
    Hartmut Pfitzinger over 3 years
    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!