【问题标题】:Format number from Zero to Six decimal points in PHPPHP中从零到六位小数的格式数字
【发布时间】:2018-01-06 13:35:33
【问题描述】:

我想显示最多 6 个小数点的数字。

像这样:

99.0000001 -> 99
99.000001  -> 99.000001
99.00001   -> 99.00001
99.0001    -> 99.0001
99.001     -> 99.001
99.01      -> 99.01
99.10      -> 99.10
99.00      -> 99

在 PHP 中执行此操作的优雅方法是什么?

【问题讨论】:

  • number_format()
  • 简单的 number_format() 不起作用。

标签: php number-formatting


【解决方案1】:

使用round(),精度为6

<?php
echo round(99.0000001, 6).PHP_EOL;
echo round(99.000001, 6).PHP_EOL;
echo round(99.00001, 6).PHP_EOL;
echo round(99.0001, 6).PHP_EOL;
echo round(99.001, 6).PHP_EOL;
echo round(99.01, 6).PHP_EOL;
echo round(99.10, 6).PHP_EOL;
echo round(99.00, 6).PHP_EOL;

https://3v4l.org/5lWCa

结果:

99
99.000001
99.00001
99.0001
99.001
99.01
99.1
99

【讨论】:

    【解决方案2】:

    你可以使用它。 删除第 6 位小数后的加法数字。

    $z = 99.0000011;  
    $y = floor($z * 1000000) / 1000000;
    

    然后计算小数点后的位数。

    $str = "$y";
    $dcount = strlen(substr(strrchr($str, "."), 1));
    

    现在我们必须确定该值是否应该有小数,如果是,则需要有 2 个或更多小数。

    $a = 0; 
    If ($dcount == 1) {$a = $dcount+1;} 
    else {$a = $dcount;} 
    $x = number_format((float)$y, $a, '.', '');
    

    $x 将是您正在寻找的所需结果。

    【讨论】:

    • 谢谢。这就是我的想法。我想知道是否有更好/更优雅的方式......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    • 2013-09-24
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多