【问题标题】:PHP enter percentage number round to 2 decimal places not workingPHP输入百分比数字四舍五入到小数点后2位不起作用
【发布时间】:2017-01-19 04:41:33
【问题描述】:

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

【问题讨论】:

  • 你是说你想要返回的最小值是 0.01..?

标签: php math rounding


【解决方案1】:

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

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

【讨论】:

  • 这适用于所有情况,但在一种情况下,如果 x 为 0,则函数将返回 0.01,因此会导致问题
【解决方案2】:

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

【讨论】:

  • 所以没有解决办法?
  • 这与是否有解决方案无关。你试图达到的目标是错误的。它会给你错误的结果。
  • 我知道我的预期结果是错误的,但根据输入百分比,我必须这样做以进行进一步处理
  • 您可以使用 0.00000000000000000000001 进一步处理,然后尝试将最终结果四舍五入。
【解决方案3】:

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

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

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

【讨论】:

  • 所以没有解决办法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-12
  • 2012-01-03
  • 1970-01-01
  • 1970-01-01
  • 2012-08-29
  • 2015-11-24
相关资源
最近更新 更多