Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing floats - same number, but does not equal? [duplicate]

Possible Duplicate:
How should I do floating point comparison?
php integer and float comparison mismatch

I have two variables, $_REQUEST['amount'] and $carttotal, on an e-commerce thing. They of course should match when attempting to process a payment, so as to prevent a manual override of the payment amount at the last minute, or of course, a calculation error.

However:

$carttotal = $carttotal * 1;
$_REQUEST['amount'] = $_REQUEST['amount'] * 1;

if($carttotal != $_REQUEST['amount']) {
    $code = 0; // cart empty under this user - cannot process payment!!! 
    $message = 'The cart total of ' . $carttotal . ' does not match ' . $_REQUEST['amount'] . '. Cannot process payment.';
    $amount = $carttotal;
    $json = array('code' => $code,
                  'message' => $message,
                  'amount' => $amount);
    die(json_encode($json));
} else {
    $trnOrderNumber = $client->id . '-' . $carttotal;
}

The above code, with the same numbers passed, is NOT giving me the equal. Basically I get the error message as if the $carttotal != $_REQUEST['amount'] is true (unequal vars).

So to test the vars, I snuck in:

var_dump($_REQUEST['amount']);
var_dump($carttotal);

To see what is going on (after I do the * 1 calculations to make sure they are dealt with as floats, not strings).

I got this back:

float(168.57)
float(168.57)

Very very frustrating. What could be causing this?

like image 416
jeffkee Avatar asked Dec 02 '11 23:12

jeffkee


2 Answers

floating point numbers have limited precision. view the warning about comparing them here:

http://php.net/manual/en/language.types.float.php

like image 55
dqhendricks Avatar answered Oct 16 '22 19:10

dqhendricks


Floating point numbers are NOT 100% accurate! You calculation in PHP may return 10.00000000001 which is NOT equal to 10.

Use sprintf ( http://php.net/manual/en/function.sprintf.php ) to format the floats before you compare them.

like image 33
Oliver A. Avatar answered Oct 16 '22 19:10

Oliver A.