如何在没有 number_format() 的情况下为 php 中的“echo”设置更多 12 位浮点精度?

问题描述 投票:0回答:3

PHP代码:

$val1 = 32;
$val2 = 0.00012207031255;
$res = $val1 - $val2;
echo "echo: ".$res."\n";
echo "json: ".json_encode($res)."\n";
echo "form: ".number_format($res, 14);

输出:

echo: 31.999877929687
json: 31.99987792968745
form: 31.99987792968745

如何在没有

number_format()

的echo中显示14位小数

我尝试在

precision=14
中设置
php.ini
但没有任何改变

php precision
3个回答
1
投票

如果你想在不改变每一行代码的情况下为整个项目添加一个全局解决方案,你可以在引导文件中设置

ini_set('precision', 14)
或者在php.ini中设置相同的值。

要格式化单个值,您可以使用具有 14 个十进制字符格式的

sprintf()
函数。

代码:

$val1 = 32;
$val2 = 0.00012207031255;
$res = $val1 - $val2;
echo sprintf("echo: %.14f\n", $res);
echo "json: ".json_encode($res)."\n";
echo "form: ".number_format($res, 14);

结果:

echo: 31.99987792968745
json: 31.99987792968745
form: 31.99987792968745

0
投票

可以尝试使用数学php模块函数:

php > $a = 32;

php > $b = 0.00012207031255;

php > echo bcsub($a, $b, 14);
31.99987792968745

更多详情在这里


0
投票

你可以使用 sprintf()

$val1 = 32;
$val2 = 0.00012207031255;
$res = $val1 - $val2;
echo "echo: ".rtrim(sprintf("%.14f", $res), "0")."\n";
© www.soinside.com 2019 - 2024. All rights reserved.