在 PHP 中设置浮点数的精度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19875583/
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
Set precision for a float number in PHP
提问by Mostafa Talebi
I get a number from database and this number might be either float
or int
.
I need to set the decimal precision of the number to 3
, which makes the number not longer than (regarding decimals) 5.020
or 1518845.756
.
我从数据库中得到一个数字,这个数字可能是float
或int
。
我需要将数字的小数精度设置为3
,这使得数字不长于(关于小数)5.020
或1518845.756
。
Using PHP
使用 PHP
round($number, $precision)
I see a problem:
我看到一个问题:
It rounds the number. I need a function to only cut the decimals short, without changing their values which round( )
seems not to follow.
它对数字进行四舍五入。我需要一个函数来只截短小数,而不改变它们round( )
似乎不遵循的值。
回答by Amal Murali
You can use number_format()
to achieve this:
您可以使用以下方法number_format()
来实现:
echo number_format((float) $number, $precision, '.', '');
This would convert 1518845.756789
to 1518845.757
.
这将转换1518845.756789
为1518845.757
.
But if you just want to cut off the number of decimal places short to 3, and notround, then you can do the following:
但是,如果您只想将小数位数缩短为 3,而不是round,那么您可以执行以下操作:
$number = intval($number * ($p = pow(10, $precision))) / $p;
It may look intimidating at first, but the concept is really simple. You have a number, you multiply it by 103(it becomes 1518845756.789
), cast it to an integer so everything after the 3 decimal places is removed (becomes 1518845756
), and then divide the result by 103(becomes 1518845.756
).
乍一看可能有点吓人,但概念其实很简单。您有一个数字,将其乘以 10 3(变为1518845756.789
),将其转换为整数,以便删除小数点后 3 位后的所有内容(变为1518845756
),然后将结果除以 10 3(变为1518845.756
)。
回答by georgecj11
Its sound like floor
with decimals. So you can try something like
它听起来像floor
小数。所以你可以尝试类似的东西
floor($number*1000)/1000
回答by Uours
If I understand correctly, you would not want rounding to occur and you would want the precision to be 3.
如果我理解正确,您不会希望发生四舍五入,并且您希望精度为 3。
So the idea is to use number_format()
for a precision of 4 and then remove the last digit:
所以这个想法是使用number_format()
4 的精度,然后删除最后一个数字:
$number = '1518845.756789';
$precision = 3;
echo substr(number_format($number, $precision+1, '.', ''), 0, -1);
Will display:
将显示:
1518845.756
rather than:
而不是:
1518845.757
Links : number_format()
, substr()
回答by Derezzed
See this answerfor more details.
有关更多详细信息,请参阅此答案。
function numberPrecision($number, $decimals = 0)
{
$negation = ($number < 0) ? (-1) : 1;
$coefficient = pow(10, $decimals);
return $negation * floor((string)(abs($number) * $coefficient)) / $coefficient;
}
回答by Pavla
$num=5.1239;
$testnum=intval($num*1000)/1000;
echo $testnum; //return 5.123