简体   繁体   English

比较两个浮点值-不相同

[英]Compare two float values - not identical

I´ve a strange problem and I hope you can help me. 我有一个奇怪的问题,希望您能帮助我。

I´ve two values at the beginning: 一开始我有两个值:

var_dump($order_sum);
var_dump($orders_obj->getOrders_preisliste_sum ());
var_dump($order_sum != $orders_obj->getOrders_preisliste_sum ());

Result: 结果:

float(49.7) 
string(7) "49.7000" 
bool(true)

Here all is okay, but why is that way also "true" if I compare them? 一切都很好,但是如果我将它们进行比较,那为什么还这样呢?

var_dump($order_sum);
var_dump(floatval($orders_obj->getOrders_preisliste_sum ()));
var_dump($order_sum != floatval($orders_obj->getOrders_preisliste_sum ()));

Result: 结果:

float(49.7) 
float(49.7) 
bool(true) <---

In my opinion it should be the same, but here PHP displays it as a different. 我认为应该是相同的,但是在这里PHP将其显示为不同的内容。

You could use bccomp function (bcmath extension) to compare your float values : http://www.php.net/manual/en/function.bccomp.php . 您可以使用bccomp函数(bcmath扩展名)比较您的浮点值: http ://www.php.net/manual/zh/function.bccomp.php。 Your values are actually not equals because of floating point precision as Adam just mentioned. 正如亚当刚提到的那样,由于浮点精度,您的值实际上并不等于。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM