首页 > Web开发 > 详细

PHP浮点数精度问题

时间:2015-07-04 16:42:36      阅读:477      评论:0      收藏:0      [点我收藏+]

这一段时间维护一个类似团购的系统,需要处理订单,也就难免会处理金额 所以有很多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但也算处理的效果达到了、

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

 

PHP浮点数精度问题

原文:http://www.cnblogs.com/jso0/p/4620820.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!