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:

1 2 3 4 5 6 7 8 9 |
class Util { public static void main(String[] args) { float x = 5.60f; int y = (int)x; System.out.println("y = " + y); } } |

`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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class Util { public static void main(String[] args) { float x = 5.60f; int y; if (x >= 0.0f) { // x is positive y = (int) (x + 0.5); } else { // x is negative y = (int)(x - 0.5); } System.out.println("y = " + y); } } |

`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.

1 2 3 4 5 6 7 8 9 |
class Util { public static void main(String[] args) { float x = 5.60f; int y = Math.round(x); System.out.println("y = " + y); } } |

`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