比较花车 - 相同的数字,但不等于? [英] Comparing floats - same number, but does not equal?

查看:151
本文介绍了比较花车 - 相同的数字,但不等于?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

我应该如何做浮点比较?


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)

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

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



http://php.net/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:

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

这篇关于比较花车 - 相同的数字,但不等于?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆