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 returned. If you pass a float value to the Math.round() method, an int result is returned. The Math.round() method will round a value up if the decimal portion of the floating point number is 0.5 or greater, and it will be rounded down for decimal numbers less than 0.5.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net