您可以通过在PHP中舍入两个浮点数来安全地比较两个浮点数吗? [英] Can you safely compare two floats by rounding them in PHP?

查看:55
本文介绍了您可以通过在PHP中舍入两个浮点数来安全地比较两个浮点数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您是否可以通过将两个舍入到所需的精度来可靠地比较两个浮点的等效性,而不是使用epsilon进行浮点比较?

Rather than using an epsilon for float comparison, can you reliably compare two floats for equivalency by rounding them to the desired precision?

例如:

round($float, 3) === round($otherFloat, 3)

推荐答案

否.如果您的数字刚好在函数的四舍五入而不是四舍五入的值的相对两端(如果四舍五入为最接近的整数,则为半整数),则无论它们之间的距离如何接近,它们都将四舍五入是.

No. If your numbers are just barely on opposite sides of the value where the function will round up instead of down (a half-integer if you're round to the nearest integer), then they will round to different numbers no matter how close together they are.

这篇关于您可以通过在PHP中舍入两个浮点数来安全地比较两个浮点数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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