比较浮点数 - 相同的数字,但不相等?

时间:2011-12-02 23:56:53

标签: php floating-point

  

可能重复:
  How should I do floating point comparison?
  php integer and float comparison mismatch

我在电子商务方面有两个变量$_REQUEST['amount']$carttotal。当然,它们在尝试处理付款时应该匹配,以防止在最后一分钟手动覆盖支付金额,或者当然是计算错误。

然而:

$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;
}

上面的代码,通过相同的数字,并没有给我平等。基本上我收到错误消息,好像$carttotal != $_REQUEST['amount']true(不等的变量)。

所以为了测试变量,我偷偷地进来了:

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

要查看发生了什么(在我进行* 1计算之后确保将它们作为浮点数处理,而不是字符串处理)。

我得到了回复:

float(168.57)
float(168.57)

非常非常令人沮丧。可能是什么导致了这个?

3 个答案:

答案 0 :(得分:13)

浮点数的精度有限。查看有关比较它们的警告:

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

答案 1 :(得分:5)

浮点数不是100%准确! 您在PHP中的计算可能会返回10.00000000001,它不等于10.

使用sprintf(http://php.net/manual/en/function.sprintf.php)格式化浮点数,然后再进行比较。

答案 2 :(得分:0)

而不是乘以一次使用number_format。

 $carttotal = number_format((int)$carttotal,2,'.','');
 $_REQUEST['amount'] = number_format((int)$_REQUEST['amount'],2,'.','');
相关问题