1

I have two numbers: balance1 = 0.253164557e-4 (which would give 0.0000253164557) balance2 = 0.00002531

now when I compare then in ruby like: balance1 == balance2 , it gives false due to precision issue

but my requirement consider them to be equal, suggest ways to do this

engineersmnky
  • 25,495
  • 2
  • 36
  • 52
  • 1
    _"my requirement consider them to be equal"_ – what are your exact requirements? – Stefan Jun 26 '23 at 14:29
  • Do it like in mathematics: If you can not reasonably use _x=y_ for equality, test for _|x-y|<δ_, i.e. take the absolute value of the difference between the numbers and see whether it is smaller than a certain delta. – user1934428 Jun 27 '23 at 07:22
  • First you need to round numbers to the desired (required) precision (it can be 8 digits after the dot, looking at your question) then compare numbers with the delta. – rotabor Jun 27 '23 at 15:04

1 Answers1

2

Floating-point numbers are not suitable for exact comparison. Often, two numbers that should be equal are actually slightly different. One way to compare two floating-point numbers is by using a delta value. You can check if the absolute difference between the two numbers is less than or equal to the delta value. For example: (expected_float - actual_float).abs <= delta