可能重复: 我应该如何做浮点比较?
I在电子商务中有两个变量: $ _REQUEST ['amount'] 和 $ carttotal 他们当然应该在尝试处理付款时匹配,以防止在最后一分钟手动超控付款金额,当然还有一个计算错误。不过:
$ carttotal = $ carttotal * 1;$ _REQUEST ['amount'] = $ _REQUEST ['amount'] * 1; if($ carttotal!= $ _REQUEST ['amount']){ $ code = 0; //这个用户下的购物车为空 - 无法处理付款! $ message ='购物车总额'。 $ carttotal。 ' 不匹配 ' 。 $ _REQUEST ['amount']。 。无法处理付款。 $ amount = $ carttotal; $ json = array('code'=> $ code,'message'=> $ message,'amount'=> $ amount); die(json_encode($ json)); } else { $ trnOrderNumber = $ client-> id。 ' - '。 $ carttotal; $ b $ p $ b上面的代码,通过相同的数字,并不等于等于。基本上我得到的错误信息就好像 $ carttotal!= $ _REQUEST ['amount'] 是 true 乏)。
因此,为了测试这些变量,我偷偷地进入: $ b $ $ $ $ $ $ $ $ $ var_dump ($ _REQUEST [ '量']); var_dump($ carttotal);
要看看发生了什么(在执行 * 1 计算,以确保它们被处理为浮动,而不是字符串)。
$ p $ float(168.57) float(168.57)
非常令人沮丧。什么可能导致这个?
解决方案浮点数的精度有限。在这里查看关于比较它们的警告:
php/manual/en/language.types.float.php
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?
解决方案floating point numbers have limited precision. view the warning about comparing them here:
php/manual/en/language.types.float.php
更多推荐
比较花车
发布评论