PHP输入百分比数字轮到2位小数不起作用

时间:2017-01-19 04:41:33

标签: php math rounding

php号码舍入到2位小数不能正常工作我的号码是0.00000000000000000000001,我希望结果为0.01。我尝试了php number_format()函数php round()函数,但它们对我不起作用。

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

0.01远远大于0.00000000000000000000001。你不能把它四舍五入到0.01。 0.006可以四舍五入为0.01,因为它们非常接近。

答案 2 :(得分:0)

在您的情况下,Number_format()和round()将不起作用。

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

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