dpkajqd31574096 2017-02-14 17:16
浏览 76
已采纳

如何使用PHP删除十进制数

I have a code where I got some numbers like this:

92.682926829268 

I'd like to cut them like this:

92.68

This is my code:

<td><?php if (($row['TotalMatch']) > 10){ echo ($row['OK_05'] / $row['TotalMatch']) * 100; }   ?></td>

I tried with floor and round but I get that example I showed at the beginning of post ( 92.682926829268 instead of 92.68 )

Thanks for your attention

Regards!

EDIT Could you give me an example with my code? Thanks

  • 写回答

5条回答 默认 最新

  • douguabu8960 2017-02-14 19:00
    关注

    The expression you're trying to format is this:

    ($row['OK_05'] / $row['TotalMatch']) * 100
    

    So whichever function you decide to use needs to go around that expression.

    As to which function to use, you need to select one that returns a string, not a float.

    If you use round, and your expression returns a float that rounds to a number with two zeros after the decimal point, the trailing zeros will not be displayed in the result. For example, echo round(92.0006829268, 2) will display 92, not 92.00. So don't use round if you need to be sure that two decimal places are always displayed. round is a math function, not a formatting function.

    floor is really not useful at all here, as it returns a number with no decimal places.


    A simple way is to use sprintf as shown in some of the other answers.

    echo sprintf("%.2f", ($row['OK_05'] / $row['TotalMatch']) * 100);
    

    The first argument to sprintf is "%.2f", which is a format string indicating that the second argument should be displayed as a float with two decimal places. The second argument is your expression.

    Using bcdiv as suggested in the other answer will also work, but it works a little differently that sprintf and will produce a slightly different result in some cases.

    sprintf will round to the number of decimal places specified, so for example

    echo sprintf("%.2f", 926.89 / 10);   // outputs 92.69
    

    and bcdiv will truncate instead, so

    echo bcdiv(926.89, 10, 2);           // outputs 92.68
    

    Whichever one of those works for you, do that.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?