请考虑以下代码:
0.1 + 0.2 == 0.3 -> false
Run Code Online (Sandbox Code Playgroud)
0.1 + 0.2 -> 0.30000000000000004
Run Code Online (Sandbox Code Playgroud)
为什么会出现这些不准确之处?
我想在PHP中比较两个浮点数,如下面的示例代码:
$a = 0.17;
$b = 1 - 0.83; //0.17
if($a == $b ){
echo 'a and b are same';
}
else {
echo 'a and b are not same';
}
Run Code Online (Sandbox Code Playgroud)
在此代码它返回的结果else条件,而不是if条件,即使$a和$b相同.在PHP中有没有特殊的方法来处理/比较浮点数?
如果是,那么请帮我解决这个问题.
或者我的服务器配置有问题吗?
可能重复:
我应该如何进行浮点比较?
php整数和浮点数比较不匹配
我有两个变量,$_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 . …Run Code Online (Sandbox Code Playgroud)