PHP 如何四舍五入到小数点后两位?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12277945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP How do I round down to two decimal places?
提问by Adam Moss
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 substrbecause 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.
非常感谢任何帮助。
回答by GeoffreyB
This can work: floor($number * 100) / 100
这可以工作: floor($number * 100) / 100
回答by huysentruitw
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);
}
回答by Alex
Unfortunately, none of the previous answers (including the accepted one) works for all possible inputs.
不幸的是,之前的答案(包括接受的答案)都不适用于所有可能的输入。
1) sprintf('%1.'.$precision.'f', $val)
1) sprintf('%1.'.$precision.'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) floor($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.
此函数适用于正数和负数,以及所需的任何精度。
回答by GordonM
Multiply your input by 100, floor() it, then divide the result by 100.
将您的输入乘以 100, floor() 它,然后将结果除以 100。
回答by Jamie Robinson
I think there is quite a simple way to achieve this:
我认为有一种非常简单的方法可以实现这一目标:
$rounded = bcdiv($val, 1, $precision);
Here is a working example. You need BCMath installed but I think it's normally bundled with a PHP installation. :) Here is the documentation.
回答by Sanaullah Ahmad
You can use bcdiv PHP function.
您可以使用 bcdiv PHP 函数。
bcdiv(49.955, 1, 2)
回答by Sterling Beason
function roundDown($decimal, $precision)
{
$sign = $decimal > 0 ? 1 : -1;
$base = pow(10, $precision);
return floor(abs($decimal) * $base) / $base * $sign;
}
// Examples
roundDown(49.955, 2); // output: 49.95
roundDown(-3.14159, 4); // output: -3.1415
roundDown(1000.000000019, 8); // output: 1000.00000001
This function works with positive and negative decimals at any precision.
此函数适用于任何精度的正小数和负小数。
Code example here: http://codepad.org/1jzXjE5L
这里的代码示例:http: //codepad.org/1jzXjE5L
回答by user1606963
回答by Yatish Balaji
function floorToPrecision($val, $precision = 2) {
return floor(round($val * pow(10, $precision), $precision)) / pow(10, $precision);
}
回答by Luke Cousins
An alternative solution using regex which should work for all positive or negative numbers, whole or with decimals:
使用正则表达式的替代解决方案应该适用于所有正数或负数,整数或小数:
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');
}

