Summer Developer Summer Developer - 3 months ago 11x
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

that it won't then charge the customer
dollars but will instead return an error using Laravel's
. My problem is even when the client-side
and the
seem to be correct and identical when echoing them out, I still get the

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);

The thing is on the abort my response is:

Your Order Cost Is Incorrect!46.45 46.45

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


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.