Search

Friday, October 16, 2015

How to convert float to int in Java? Examples

Even though both float and int are 32-bit wide data type, float has the higher range than integer primitive value. Since a float is a bigger than int, you can convert a float to an int by simply down-casting it e.g. (int) 4.0f will give you integer 4. By the way, you must remember that type casting just get rid of anything after the decimal point, they don't perform any rounding or flooring operation on the value. So if your float value is 3.999, down casting to an integer will produce 3, not 4. If you need rounding then consider using Math.round() method, which converts float to its nearest integer by adding +0.5 and then truncating it. Math.random() is overloaded for both float and double, so you can use this for converting double to long as well. Let's see an example of converting a float value to int in Java.
Read more »

No comments:

Post a Comment