PHP浮点数精度问题

这一段时间维护一个类似团购的系统,需要处理订单,也就难免会处理金额 所以有很多PHP的坑 被我狠狠的踩了~~

 

首先我们要知道浮点数的表示(IEEE 754):

简言之 就是 埋下了一个大坑 等着你跳 比如处理 浮点加减法的时候

<?php
echo (53.55-(3.67+49.88));
//-7.105427357601E-15
?>

有木有感觉到深深地恶意、但是也是PHP按标准执行的 只能是迂回前进了;

解决方案:

BCMath Arbitrary Precision Mathematics 

 

  • BC Math Functions
    • bcadd — Add two arbitrary precision numbers
    • bccomp — Compare two arbitrary precision numbers
    • bcdiv — Divide two arbitrary precision numbers
    • bcmod — Get modulus of an arbitrary precision number
    • bcmul — Multiply two arbitrary precision number
    • bcpow — Raise an arbitrary precision number to another
    • bcpowmod — Raise an arbitrary precision number to another, reduced by a specified modulus
    • bcscale — Set default scale parameter for all bc math functions
    • bcsqrt — Get the square root of an arbitrary precision number
    • bcsub — 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但也算处理的效果达到了、

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 

posted @ 2015-07-04 16:14  jso0  阅读(684)  评论(0编辑  收藏  举报