0

So I am stuck on something that should be very easy, I'm hoping I'm making a simple syntax or type error that I just can't see, so I need some help.

I'm doing form validation in Laravel to make sure that if someone sends me JSON from the client with the price of an item as 0 that it won't then charge the customer 0 dollars but will instead return an error using Laravel's abort(). My problem is even when the client-side totalCost and the calculatedTotalCost seem to be correct and identical when echoing them out, I still get the abort().

Part of my code is below:

$totalCost= str_replace("$","",$totalCost);
$totalCost = (float)$totalCost;
if($calculatedTotalCost != $totalCost){
            abort(500, 'Your Order Cost Is Incorrect!'.$calculatedTotalCost." ".$totalCost);
            return;
           }

The thing is on the abort my response is:

Your Order Cost Is Incorrect!46.45 46.45

There it is, both 46.45 and I did the type conversion to a float so I don't understand why it throws the abort.

Summer Developer
  • 2,056
  • 7
  • 31
  • 68

2 Answers2

2

Maybe something about your floats make them slightly different at low decimal digits. Try replacing

if($calculatedTotalCost != $totalCost)

With something a bit more tolerant of tiny differences such as:

if(abs($calculatedTotalCost - $totalCost) > 0.001)

The basic idea is that unlike integers, floats can have tiny variations in expected outcomes from arithmetic operations. If I had to guess I would say that $calculatedTotalCost has gone through some math ops and isn't exactly what you expect. It has to do with how computers store values.From the docs:

never trust floating number results to the last digit, and do not compare floating point numbers directly for equality

The safer approach is to measure whether the difference between the values falls within an acceptable range.

BeetleJuice
  • 39,516
  • 19
  • 105
  • 165
1

For debugging this sort of problem, it's better to use var_dump than echo, since var_dump will give you information about the data type as well as just the value (as echo does).

eg. echo $a and echo $b might give you the same value, but var_dump($a, $b) is likely to show you the difference that is causing the comparison to fail.

However, there are inherent problems in comparing floating point numbers. See for example this question and this note in the PHP docs for discussion of the problem and potential solutions.

Community
  • 1
  • 1
Nick F
  • 9,781
  • 7
  • 75
  • 90