PHP我怎么把它四舍五入到小数点后两位呢?

时间:2022-06-10 08:08:11

I need to round down a decimal in PHP to two decimal places so that:

我需要把PHP中的小数四舍五入到小数点后两位:

49.955

becomes...

变得……

49.95

I have tried number_format, but this just rounds the value to 49.96. I cannot use substr because the number may be smaller (such as 7.950). I've been unable to find an answer to this so far.

我已经尝试过number_format,但这只是将值转到49.96。我不能使用substr,因为数字可能更小(比如7.950)。到目前为止,我一直找不到答案。

Any help much appreciated.

感谢任何帮助。

13 个解决方案

#1


68  

This can work: floor($number * 100) / 100

这可以工作:楼层($number * 100) / 100

#2


14  

Here is a nice function that does the trick without using string functions:

这里有一个很好的函数,不用使用字符串函数就可以做到:

<?php
function floorp($val, $precision)
{
    $mult = pow(10, $precision); // Can be cached in lookup table        
    return floor($val * $mult) / $mult;
}

print floorp(49.955, 2);
?>

An other option is to subtract a fraction before rounding:

另一种选择是在四舍五入之前减去一个分数:

function floorp($val, $precision)
{
    $half = 0.5 / pow(10, $precision); // Can be cached in a lookup table
    return round($val - $half, $precision);
}

#3


9  

Unfortunately, none of the previous answers (including the accepted one) works for all possible inputs.

不幸的是,前面的答案(包括已接受的答案)对所有可能的输入都不起作用。

1) sprintf('%1.'.$precision.'f', $val)

1)sprintf(“% 1”。美元的精度。“f”,val美元)

Fails with a precision of 2 : 14.239 should return 14.23 (but in this case returns 14.24).

精度为2:14.239的失败应该返回14.23(但是在这种情况下返回14.24)。

2) floatval(substr($val, 0, strpos($val, '.') + $precision + 1))

2) floatval(substr($val, 0, strpos($val, '.') + $precision + 1))

Fails with a precision of 0 : 14 should return 14 (but in this case returns 1)

精度为0:14的失败应该返回14(但在本例中返回1)

3) substr($val, 0, strrpos($val, '.', 0) + (1 + $precision))

3) substr($val, 0, strrpos($val, ')', 0) + (1 + $precision))

Fails with a precision of 0 : -1 should return -1 (but in this case returns '-')

精度为0:-1的失败应该返回-1(但在本例中返回'-')

4) floor($val * pow(10, $precision)) / pow(10, $precision)

4)地板($val * pow(10, $precision)) / pow(10, $precision)

Although I used this one extensively, I recently discovered a flaw in it ; it fails for some values too. With a precision of 2 : 2.05 should return 2.05 (but in this case returns 2.04 !!)

虽然我经常使用这个,但最近我发现了其中的一个缺陷;它在某些值上也失败了。精度为2:2.05应该返回2.05(但在本例中返回2.04 !)

So far the only way to pass all my tests is unfortunately to use string manipulation. My solution based on rationalboss one, is :

到目前为止,通过所有测试的唯一方法是使用字符串操作。我基于rationalboss one的解决方案是:

function floorDec($val, $precision = 2) {
    if ($precision < 0) { $precision = 0; }
    $numPointPosition = intval(strpos($val, '.'));
    if ($numPointPosition === 0) { //$val is an integer
        return $val;
    }
    return floatval(substr($val, 0, $numPointPosition + $precision + 1));
}

This function works with positive and negative numbers, as well as any precision needed.

这个函数可以处理正数和负数,以及任何需要的精度。

You can find a working example here : http://codepad.viper-7.com/ZGprQJ.

您可以在这里找到一个工作示例:http://codepad.viper-7.com/ZGprQJ。

#4


6  

Multiply your input by 100, floor() it, then divide the result by 100.

将输入乘以100(),然后除以100。

#5


2  

Try the round() function

试着圆()函数

Like this: round($num, 2, PHP_ROUND_HALF_DOWN);

如下所示:round($num, 2, PHP_ROUND_HALF_DOWN);

#6


1  

    function roundDown($decimal, $precision)
    {
        $fraction = substr($decimal - floor($decimal), 2, $precision); //calculates the decimal places to $precision length
        $newDecimal = floor($decimal). '.' .$fraction; // reconstructs decimal with new # of decimal places

        return floatval($newDecimal);
    }

    echo roundDown(345.8768378, 5); // OUTPUT: 345.87683

This function works with positive and negative numbers.

这个函数适用于正数和负数。

Code example here: http://codepad.org/RAOyBCuY

代码例子:http://codepad.org/RAOyBCuY

#7


0  

Use formatted output

使用格式化的输出

sprintf("%1.2f",49.955) //49.95

DEMO

演示

#8


0  

You can use:

您可以使用:

$num = 49.9555;
echo substr($num, 0, strpos($num, '.') + 3);

#9


0  

An alternative solution using regex which should work for all positive or negative numbers, whole or with decimals:

一种使用regex的可选解决方案,适用于所有正数或负数、整数或小数:

if (preg_match('/^-?(\d+\.?\d{1,2})\d*$/', $originalValue, $matches)){
    $roundedValue = $matches[1];
} else {
    throw new \Exception('Cannot round down properly '.$originalValue.' to two decimal places');
}

#10


0  

If you want to round the decimal down only when the last part of it is 5 or bellow then the best solution is to use:

如果你想把小数点四舍五入,当小数点的最后部分是5或以下时,最好的解决办法是:

round(4.955,2,PHP_ROUND_HALF_DOWN);

Now, if you want to always round the decimals down and still have control of the amount of decimals, best solution is:

现在,如果你想把小数点四舍五入并控制小数点的数量,最好的解决方法是:

round(floor(4.957*100)/100,2)

Also consider that the "100" number must scale togheter with the "2" decimal. E.G. If you want 4 decimals you will have to multiply by 10000 and divide by 10000 so you will only lose the numbers beyond that point.

还要考虑到“100”的数字必须与“2”的小数比例一致。例如,如果你想要4个小数,你需要乘以10000,再除以10000,这样你只会失去超过这个点的数。

#11


-1  

What about this?

这是什么?

$value = 49.955;

echo intval( $value * 100 ) / 100;

Here is a demo

这是一个演示

#12


-2  

sprintf("%1.2f",49.955) //49.95

if you need to truncate decimals without rounding - this is not suitable, because it will work correctly until 49.955 at the end, if number is more eg 49.957 it will round to 49.96
It seems for me that Lght`s answer with floor is most universal.

如果你需要截断小数而不需要四舍五入——这是不合适的,因为它将正确地工作到最后49.955,如果数字更多如49.957,它将四舍五入到49.96。

#13


-4  

Did you try round($val,2) ?

你试过($val,2)吗?

More information about the round() function

有关round()函数的更多信息

#1


68  

This can work: floor($number * 100) / 100

这可以工作:楼层($number * 100) / 100

#2


14  

Here is a nice function that does the trick without using string functions:

这里有一个很好的函数,不用使用字符串函数就可以做到:

<?php
function floorp($val, $precision)
{
    $mult = pow(10, $precision); // Can be cached in lookup table        
    return floor($val * $mult) / $mult;
}

print floorp(49.955, 2);
?>

An other option is to subtract a fraction before rounding:

另一种选择是在四舍五入之前减去一个分数:

function floorp($val, $precision)
{
    $half = 0.5 / pow(10, $precision); // Can be cached in a lookup table
    return round($val - $half, $precision);
}

#3


9  

Unfortunately, none of the previous answers (including the accepted one) works for all possible inputs.

不幸的是,前面的答案(包括已接受的答案)对所有可能的输入都不起作用。

1) sprintf('%1.'.$precision.'f', $val)

1)sprintf(“% 1”。美元的精度。“f”,val美元)

Fails with a precision of 2 : 14.239 should return 14.23 (but in this case returns 14.24).

精度为2:14.239的失败应该返回14.23(但是在这种情况下返回14.24)。

2) floatval(substr($val, 0, strpos($val, '.') + $precision + 1))

2) floatval(substr($val, 0, strpos($val, '.') + $precision + 1))

Fails with a precision of 0 : 14 should return 14 (but in this case returns 1)

精度为0:14的失败应该返回14(但在本例中返回1)

3) substr($val, 0, strrpos($val, '.', 0) + (1 + $precision))

3) substr($val, 0, strrpos($val, ')', 0) + (1 + $precision))

Fails with a precision of 0 : -1 should return -1 (but in this case returns '-')

精度为0:-1的失败应该返回-1(但在本例中返回'-')

4) floor($val * pow(10, $precision)) / pow(10, $precision)

4)地板($val * pow(10, $precision)) / pow(10, $precision)

Although I used this one extensively, I recently discovered a flaw in it ; it fails for some values too. With a precision of 2 : 2.05 should return 2.05 (but in this case returns 2.04 !!)

虽然我经常使用这个,但最近我发现了其中的一个缺陷;它在某些值上也失败了。精度为2:2.05应该返回2.05(但在本例中返回2.04 !)

So far the only way to pass all my tests is unfortunately to use string manipulation. My solution based on rationalboss one, is :

到目前为止,通过所有测试的唯一方法是使用字符串操作。我基于rationalboss one的解决方案是:

function floorDec($val, $precision = 2) {
    if ($precision < 0) { $precision = 0; }
    $numPointPosition = intval(strpos($val, '.'));
    if ($numPointPosition === 0) { //$val is an integer
        return $val;
    }
    return floatval(substr($val, 0, $numPointPosition + $precision + 1));
}

This function works with positive and negative numbers, as well as any precision needed.

这个函数可以处理正数和负数,以及任何需要的精度。

You can find a working example here : http://codepad.viper-7.com/ZGprQJ.

您可以在这里找到一个工作示例:http://codepad.viper-7.com/ZGprQJ。

#4


6  

Multiply your input by 100, floor() it, then divide the result by 100.

将输入乘以100(),然后除以100。

#5


2  

Try the round() function

试着圆()函数

Like this: round($num, 2, PHP_ROUND_HALF_DOWN);

如下所示:round($num, 2, PHP_ROUND_HALF_DOWN);

#6


1  

    function roundDown($decimal, $precision)
    {
        $fraction = substr($decimal - floor($decimal), 2, $precision); //calculates the decimal places to $precision length
        $newDecimal = floor($decimal). '.' .$fraction; // reconstructs decimal with new # of decimal places

        return floatval($newDecimal);
    }

    echo roundDown(345.8768378, 5); // OUTPUT: 345.87683

This function works with positive and negative numbers.

这个函数适用于正数和负数。

Code example here: http://codepad.org/RAOyBCuY

代码例子:http://codepad.org/RAOyBCuY

#7


0  

Use formatted output

使用格式化的输出

sprintf("%1.2f",49.955) //49.95

DEMO

演示

#8


0  

You can use:

您可以使用:

$num = 49.9555;
echo substr($num, 0, strpos($num, '.') + 3);

#9


0  

An alternative solution using regex which should work for all positive or negative numbers, whole or with decimals:

一种使用regex的可选解决方案,适用于所有正数或负数、整数或小数:

if (preg_match('/^-?(\d+\.?\d{1,2})\d*$/', $originalValue, $matches)){
    $roundedValue = $matches[1];
} else {
    throw new \Exception('Cannot round down properly '.$originalValue.' to two decimal places');
}

#10


0  

If you want to round the decimal down only when the last part of it is 5 or bellow then the best solution is to use:

如果你想把小数点四舍五入,当小数点的最后部分是5或以下时,最好的解决办法是:

round(4.955,2,PHP_ROUND_HALF_DOWN);

Now, if you want to always round the decimals down and still have control of the amount of decimals, best solution is:

现在,如果你想把小数点四舍五入并控制小数点的数量,最好的解决方法是:

round(floor(4.957*100)/100,2)

Also consider that the "100" number must scale togheter with the "2" decimal. E.G. If you want 4 decimals you will have to multiply by 10000 and divide by 10000 so you will only lose the numbers beyond that point.

还要考虑到“100”的数字必须与“2”的小数比例一致。例如,如果你想要4个小数,你需要乘以10000,再除以10000,这样你只会失去超过这个点的数。

#11


-1  

What about this?

这是什么?

$value = 49.955;

echo intval( $value * 100 ) / 100;

Here is a demo

这是一个演示

#12


-2  

sprintf("%1.2f",49.955) //49.95

if you need to truncate decimals without rounding - this is not suitable, because it will work correctly until 49.955 at the end, if number is more eg 49.957 it will round to 49.96
It seems for me that Lght`s answer with floor is most universal.

如果你需要截断小数而不需要四舍五入——这是不合适的,因为它将正确地工作到最后49.955,如果数字更多如49.957,它将四舍五入到49.96。

#13


-4  

Did you try round($val,2) ?

你试过($val,2)吗?

More information about the round() function

有关round()函数的更多信息