425

I used the following line to convert float to int, but it's not as accurate as I'd like:

 float a=8.61f;
 int b;

 b=(int)a;

The result is : 8 (It should be 9)

When a = -7.65f, the result is : -7 (It should be -8)

What's the best way to do it ?

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
Frank
  • 30,590
  • 58
  • 161
  • 244

9 Answers9

788

Using Math.round() will round the float to the nearest integer.

tw39124
  • 9,103
  • 2
  • 20
  • 14
  • 1
    why is the typecast needed after Math.round()? – necromancer Jun 09 '12 at 01:51
  • 87
    [`Math.round()`](http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Math.html#round(float)) returns `int` value so typecasting using `(int)` is redundant. – Solvek Jul 02 '12 at 18:13
  • 6
    use either/or... `(int)foo` is simpler. – yuttadhammo Jul 12 '12 at 09:39
  • 39
    Solvek's answer is right, but I'd like to point out that Math.round() can have two different output types based on the input. Math.round(double a) returns a long. Math.round(float a) returns an int. http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#round(double) – Hososugi Mar 13 '14 at 17:47
  • 3
    Math.round() is a slow operation compared to casting to (int) – Darkgaze Nov 15 '16 at 10:54
  • @darkgaze you are aware you're advocating an efficiency difference that doesn't matter in 99.99% of the applications this code would be used, right? Also, with JIT inlining, it's barely slower as soon as HotSpot hits it. –  Oct 06 '19 at 09:35
209

Actually, there are different ways to downcast float to int, depending on the result you want to achieve: (for int i, float f)

  • round (the closest integer to given float)

    i = Math.round(f);
      f =  2.0 -> i =  2 ; f =  2.22 -> i =  2 ; f =  2.68 -> i =  3
      f = -2.0 -> i = -2 ; f = -2.22 -> i = -2 ; f = -2.68 -> i = -3
    

    note: this is, by contract, equal to (int) Math.floor(f + 0.5f)

  • truncate (i.e. drop everything after the decimal dot)

    i = (int) f;
      f =  2.0 -> i =  2 ; f =  2.22 -> i =  2 ; f =  2.68 -> i =  2
      f = -2.0 -> i = -2 ; f = -2.22 -> i = -2 ; f = -2.68 -> i = -2
    
  • ceil/floor (an integer always bigger/smaller than a given value if it has any fractional part)

    i = (int) Math.ceil(f);
      f =  2.0 -> i =  2 ; f =  2.22 -> i =  3 ; f =  2.68 -> i =  3
      f = -2.0 -> i = -2 ; f = -2.22 -> i = -2 ; f = -2.68 -> i = -2
    
    i = (int) Math.floor(f);
      f =  2.0 -> i =  2 ; f =  2.22 -> i =  2 ; f =  2.68 -> i =  2
      f = -2.0 -> i = -2 ; f = -2.22 -> i = -3 ; f = -2.68 -> i = -3
    

For rounding positive values, you can also just use (int)(f + 0.5), which works exactly as Math.Round in those cases (as per doc).

You can also use Math.rint(f) to do the rounding to the nearest even integer; it's arguably useful if you expect to deal with a lot of floats with fractional part strictly equal to .5 (note the possible IEEE rounding issues), and want to keep the average of the set in place; you'll introduce another bias, where even numbers will be more common than odd, though.

See

http://mindprod.com/jgloss/round.html

http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html

for more information and some examples.

  • rint is banker's rounding; it helps reduce errors that can appear if you consistently round 0.5 up or down. – prosfilaes Oct 06 '19 at 09:05
  • @prosfilaes I've changed the wording & added a wiki link to that part of the answer. –  Oct 06 '19 at 09:37
16

Math.round(value) round the value to the nearest whole number.

Use

1) b=(int)(Math.round(a));

2) a=Math.round(a);  
   b=(int)a;
Quest
  • 2,764
  • 1
  • 22
  • 44
13

Instantiate a Float object by passing a float primitive to the constructor, then use the Float object you created to return an int primitive.

Explanation
Since number wrapper classes extend the java.lang.Number class, you can have any number wrapper object return any other number primitive type by using the .<type>Value() method.

Steps

  1. Create a Float object
  2. Use the .intValue() method to return a primitive int.

Example

Float mFloat = Float.valueOf(8.65f);
int i = mFloat.intValue();
ike5
  • 188
  • 1
  • 10
7

Math.round also returns an integer value, so you don't need to typecast.

int b = Math.round(float a);
midor
  • 5,487
  • 2
  • 23
  • 52
venkat
  • 111
  • 1
  • 1
6

Use Math.round(value) then after type cast it to integer.

float a = 8.61f;
int b = (int)Math.round(a);
JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
6

Math.round() is sufficient

int b = Math.round(a)

This will do the Job

2

If you want to convert a float value into an integer value, you have several ways to do it that depends on how do you want to round the float value.

First way is floor rounding the float value:

float myFloat = 3.14f;
int myInteger = (int)myFloat;

The output of this code will be 3, even if the myFloat value is closer to 4.

The second way is ceil rounding the float value:

float myFloat = 3.14f;
int myInteger = Math.ceil(myFloat);

The output of this code will be 4, because the rounding mode is always looking for the highest value.

-2

As to me, easier: (int) (a +.5) // a is a Float. Return rounded value.

Not dependent on Java Math.round() types

Bruno L.
  • 457
  • 6
  • 8
  • 4
    This will confuse a lot developers that analyze the code. It will not be clear it is rounding. – ivan.panasiuk Feb 01 '18 at 17:57
  • 1
    Of course it is, it s just basic mathematics, just try – Bruno L. Feb 02 '18 at 01:03
  • 4
    "Basic mathematics" is a relative term. :) By my experience, I can bet that more than 50% of developers will not understand that it is really rounding. It is mathematically correct, but as I wrote, it is not clear and it is hard for others to understand what the code does. – ivan.panasiuk Feb 04 '18 at 04:03
  • 2
    `-(int) ( PI / 3 )`: try your code with a negative `a`... since when `-0.5` rounds to `0`? –  Mar 08 '18 at 19:19
  • 1
    you re right if the number is negative you must add -0.5 instead – Bruno L. Mar 10 '18 at 03:16