Skip to content

Instantly share code, notes, and snippets.

@brandondrew
Created June 15, 2024 23:08
Show Gist options
  • Save brandondrew/bd64d01d058135f711d81fb3ce719018 to your computer and use it in GitHub Desktop.
Save brandondrew/bd64d01d058135f711d81fb3ce719018 to your computer and use it in GitHub Desktop.
Safely compare floats
## you presumably already know that this returns false, because of the way floats are stored:
0.1 + 0.2 == 0.3
# => false
# we can create a more useful way of comparing floats that matches what humans would expect:
class Float
def =~(number, tolerance = 0.0001)
(self - number).abs < tolerance
end
end
## here's an example of typical usage:
0.1 + 0.2 =~ 0.3
# => true
## if you need to change the tolerance,
## use a dot like with normal methods:
(0.1 + 0.2).=~ 0.3, 0.00000000001
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment