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

0

3 Answers 3

4

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 
Sign up to request clarification or add additional context in comments.

Comments

2

It is a bit dirty but it works:

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

See the result here

3 Comments

what's the motivation behind the downvoting?
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
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
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.