PHP 输入百分比数字四舍五入到小数点后 2 位无效

PHP enter percentage number round to 2 decimal places not working

php 数字四舍五入到小数点后 2 位不工作我的数字是 0.00000000000000000000001,我希望结果为 0.01。我尝试了 php number_format() function php round() 功能,但它们对我不起作用。

Number_format() 和 round() 不适用于您的情况。

此函数根据原始数学规则调整小数位

在您的情况下,结果将始终为 0.00...因为 .01 将转换为 0.0

0.01 远远大于 0.00000000000000000000001。您不能将其四舍五入为 0.01。 0.006 可以四舍五入为 0.01,因为它们彼此非常接近。

只需创建一个简单的函数,returns 您想要的舍入值或最小值...

function round_special($x)
{
    if ($x == 0) return 0;

    $rounded = round($x, 2);
    $minValue = 0.01;

    if ($rounded < $minValue) {
        return number_format($minValue, 2);
    } else {
        return number_format($rounded, 2);
    }
}

因此,结果如下:

$x = 0.00000000000000000000001;
echo round_special($x);     // 0.01

echo round_special(0.0001); // 0.01
echo round_special(55);     // 55.00
echo round_special(0.6);    // 0.06