4

I need to convert a float number into an integer.

Can Java automatically convert float number into integers? If so, do normal rounding rules apply (e.g. 3.4 gets converted to 3, but 3.6 gets converted to 4)?

SomethingDark
  • 13,229
  • 5
  • 50
  • 55
Marko Petričević
  • 333
  • 2
  • 9
  • 20

3 Answers3

3

You have in Math library function round(float a) it's round the float to the nearest whole number.

int val = Math.round(3.6); \\ val = 4
int val2 = Math.round(3.4); \\ val2 = 3
Roy Shmuli
  • 4,979
  • 1
  • 24
  • 38
2

It is a bit dirty but it works:

double a=3.6;
int b = (int) (a + 0.5);

See the result here

cloudy_weather
  • 2,837
  • 12
  • 38
  • 63
  • what's the motivation behind the downvoting? – cloudy_weather Mar 28 '15 at 10:00
  • 3
    I didn't downvote you, but your solution wouldn't even compile, the result of `(int) a + 0.5` is of type double, which can't be assinged to an `int` have a try – morgano Mar 28 '15 at 10:10
  • 1
    anyone who knows java with a bit of good sense would realise where the compilation error was before my edit, and would get the logic behind my answer. However, I have edited it and provided a link that shows it working and compiling – cloudy_weather Mar 28 '15 at 10:17
0

Math.round(3.6) would do that for you.

Ori Lentz
  • 3,668
  • 6
  • 22
  • 28