这一段时间维护一个类似团购的系统,需要处理订单,也就难免会处理金额 所以有很多PHP的坑 被我狠狠的踩了~~
首先我们要知道浮点数的表示(IEEE 754):
简言之 就是 埋下了一个大坑 等着你跳 比如处理 浮点加减法的时候
<?php
echo (53.55-(3.67+49.88));
//-7.105427357601E-15
?>
有木有感觉到深深地恶意、但是也是PHP按标准执行的 只能是迂回前进了;
解决方案:
BCMath Arbitrary Precision Mathematics
- — Add two arbitrary precision numbers
- — Compare two arbitrary precision numbers
- — Divide two arbitrary precision numbers
- — Get modulus of an arbitrary precision number
- — Multiply two arbitrary precision number
- — Raise an arbitrary precision number to another
- — Raise an arbitrary precision number to another, reduced by a specified modulus
- — Set default scale parameter for all bc math functions
- — Get the square root of an arbitrary precision number
- — Subtract one arbitrary precision number from another
具体用法也是很简单 例如
<?php
// echo (53.55-(3.67+49.88));
echo (floatval(bcsub(bcadd(3.67,49.88),53.55)));
//-0
?>
虽说是-0但也算处理的效果达到了、
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~