Rounding Floating Point Numbers

// rounding a double value
											long longResult = Math.round(doubleValue);
											// rounding a float value
											int intResult = Math.round(floatValue);

If you want to convert a floating point number to an integer, you have to be careful. If you simply cast the floating point number to an int or long, Java will convert it to an int or long by just truncating the decimal portion. So even if you had a value such as 20.99999, you’d end up with 20 after casting it to an int or long value. The proper way to perform floating point number to integer conversion is to use the Math.round() method. In this phrase, we show how to round a double value and a float value. If you pass a double value to the Math.round() method, a long result is ...

Get Java™ Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.