Is it wrong to use the == operator when comparing float in Java?

Asked 1 years ago, Updated 1 years ago, 141 views

Here java.According to the sun page, == is an equivalent comparison operator for floating point number in Java.

However, write these codes in the editor:

if(sectionID == currentSectionID)

When I run Static analysis, the message "JAVA0078 Floating point values combined with ==" appears.

What is wrong with using the == operator to compare floating point values? What is the right way?

floating-accuracy java equality

2022-09-22 22:01

1 Answers

This is the correct way to test float for 'equal' :

if(Math.abs(sectionID - currentSectionID) < epsilon)

epsilon is as small as 0.00000001. Depending on the accuracy you want, it can be smaller or larger.


2022-09-22 22:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.