laracoft's avatar

Failing test

Failed asserting that 2000.0000000000005 matches expected 2000.0.

->assertSet('balance', 2000.00) // part of Livewire::

  1. I took over a project with this failing test
  2. Both the $actual and $expected have the gettype() of double and when inspected using XDebug, both are 2000
  3. Because both are 2000, my expectation is for assetSet('balance', 2000.00) to pass without additional code
  4. The offending line code is https://github.com/sebastianbergmann/comparator/blob/146dc7bb46c39d8d42bb0fd8cfdec588f0814f66/src/NumericComparator.php#L39-L44, where $actual - $expected is not 0
  5. Any idea what the issue might be?
0 likes
14 replies
Snapey's avatar

the perils of floating point numbers

laracoft's avatar

@tykus

Sorry, that would be hiding the problem deeper. I would like to know why 2000 is not equal to 2000.

laracoft's avatar

@tykus

Here is my logic:

  1. The tests only broke sometime in the last 3 years
  2. I also cannot reconcile the XDebug screenshot from my VSCode
  3. So, what can I do to make them pass without touching the code unnecessarily
tykus's avatar

@laracoft

The tests only broke sometime in the last 3 years

Not particularly useful tests in that case!

I also cannot reconcile the XDebug screenshot from my VSCode

Nor can I. I don't know your code or how these values are arrived at.

So, what can I do to make them pass without touching the code unnecessarily

If you want to compare floating point numbers, I suggest you impose some delta which determines how precise the comparison should be. You can see the delta is very very small in your case!

laracoft's avatar

@tykus

Would you know why XDebug is showing only 2000 instad of 2000.0000000000000x?

Snapey's avatar

There is no point arguing, you cannot compare that two differently generated floating point numbers are exactly the same.

Your 1st mistake

->assertSet('balance', 2000.00)

NEVER use floating point for currency/monetary calculations

laracoft's avatar

@Snapey

Nobody is arguing here, I would like to know how to move forward by understanding why XDebug is hiding the problem or anything else. Overhauling the code is the last resort.

1 like
tykus's avatar

@laracoft

Overhauling the code is the last resort

No-one suggested overhauling the code, just setting your expectations correctly!

Please or to participate in this conversation.