在PHP和WordPress中显示没有指数形式的小数字



是否可以在没有指数形式的情况下显示微小的数字?

<?php 
$a=4;
$b=799999999999999;
$c=$a/$b;
echo $c;
?>

我在WordPress页面(启用PHP(中使用此代码,它输出5.0E-15而不是0,0000000000000005

我使用没有自定义函数的默认 Twenty Sixteen 主题。

您将如何编辑上面的PHP代码以显示正确的数字?

您可以使用number_format函数来实现此目的。

<?php 
$a=4;
$b=799999999999999;
$c=$a/$b;
$d = number_format($c, 15, ',', '');
echo $d;
?>

输出:

0,000000000000005但正如您所说,您需要一个更动态的解决方案,因为小数位不是固定的。所以这是我提出的解决方案。

长版本:

<?php 
$a=4;
$b=799999999999999;
$c=$a/$b;
$e = 0; //this is our output variable
if((strpos($c, 'E'))){ //does the result contain an exponent ?
$d = explode("-",$c); //blow up the string and find what the decimal place is too
$e = number_format($c, $d[1], ',', ''); //format with the decimal place
}else{
$e = $c; //Number didn't contain an exponent, return the number
}
echo $e;  
?>

这是前面的代码缩短了一点:

<?php 
$a=4;
$b=799999999999999;
$c=$a/$b;
$d = (strpos($c,'E')) ? number_format($c,explode("-",$c)[1],',','') : $c;
echo $d;
?>

(我删除了我的答案并重新发布,因为我不确定您是否收到我修改了答案的警报(

最新更新