Summer Developer Summer Developer - 4 months ago 19
PHP Question

Laravel PHP Variables Appear To Be Equal On Echo But Not in Comparison Statement

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.

Answer

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.

Comments