Dave's Brain

Browse - Programming Tips - What's the best way to convert a float to an int?

Date: 2016may20
Language: Java
Level: Beginner

Q.  What's the best way to convert a float to an int?

A.	Use Math.round() like this

float f = 55.6; int i = Math.round(f); // Will be 56
This is the simplest way, but not the best:
int i = (float)f;
You can make your own round like this:
int i = (float)f + .5f; // Homemade round, use read Math.round() to be clear
If you don't want to round you can also do:
int i = Math.ceil(f); int i = Math.floor(f);

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.