zoukankan      html  css  js  c++  java
  • 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但也算处理的效果达到了、

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

  • 相关阅读:
    7. 流程控制
    6. 工作区域与包
    5. Go函数
    4. Go常量
    面试题1
    数据库三范式
    触发器和存储过程
    面试题
    js 程序执行与顺序实现详解 ,来自网上
    基础的优化数据库查询,个人笔记
  • 原文地址:https://www.cnblogs.com/jso0/p/4620820.html
Copyright © 2011-2022 走看看