Comparing Floating Point Numbers

Float a = new Float(3.0f);
											Float b = new Float(3.0f);
											if (a.equals(b)) {
											// they are equal
											}

Because of rounding errors that can occur when working with floating point numbers, you have to be a bit more careful when trying to compare them. Therefore, instead of comparing the basic Java floating point types of float and double using the == operator; you should instead compare their object equivalents. The equals() method on Float and Double will return true only if the two values are exactly the same, bit for bit, or if they are both the value NaN. The value NaN stands for not a number. This value indicates a value that is not a valid number.

In the real world, when comparing floating point numbers, you might not ...

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.