Convert float to int to nearest integer in Java

In this post, we will see how to convert float to int to nearest integer in Java.


 

For example, when x = 5.60f, the output should be 6 and for x = -5.60f, the output should be -6.

 

1. Typecasting

We know that typecasting truncates the value and won’t round the value to the nearest integer as shown below:

 

Download   Run Code

Output:

y = 5

 

But there is a workaround. For rounding the positive values, we can use the expression
(int)(x + 0.5), and for rounding the negative values, we can use the expression (int)(x - 0.5), where x is the given floating point number.

 

Download   Run Code

Output:

y = 6

 

2. Math.round()

The standard solution is to use Math class which provides round() method for floating-point approximation of a decimal number.

 

Download   Run Code

Output:

y = 6

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of