我正在尝试通过删除不必要的零来格式化最多 8 位小数的特定数字。
我的实际代码是:
rtrim(sprintf("%.8f", $upto_eight_decimals), '0')
它实际上可以防止将数字格式化为 0.00012 为 1.2E-4 或 0.00012000
但是,对于诸如 1之类的数字整数,它会转换为 1。 但这一点不是我的预期结果(我知道因为 rtrim 删除了所有零)。
更新:rtrim(rtrim(sprintf("%.8f", $upto_eight_decimals), '0'), '.')
看起来可以工作
你可以
这样做,只需使用number_format:
$upto_eight_decimals = "0.0001200";
$out = number_format((float)$upto_eight_decimals, 8, '.', '');
echo preg_replace("/'.?0*$/",'',$out);
or
echo $out + 0;
此函数返回一个字符串。
这将对您有用,让我知道它是否有效。