比较花车

编程入门 行业动态 更新时间:2024-10-21 16:33:00
本文介绍了比较花车 - 相同的数字,但不等于?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能重复: 我应该如何做浮点比较?

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

更多推荐

比较花车

本文发布于:2023-11-15 21:35:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1598159.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:花车

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!