如何在PHP中四舍五入/限制/下底bcmath数? [英] How to round/ceil/floor a bcmath number in PHP?
本文介绍了如何在PHP中四舍五入/限制/下底bcmath数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有用于此目的的任何库函数,所以我不手工做,否则可能会以TDWTF结尾?
Is there any library function for this purpose, so I don't do it by hand and risk ending in TDWTF?
echo ceil(31497230840470473074370324734723042.6);
// Expected result
31497230840470473074370324734723043
// Prints
<garbage>
推荐答案
这将为您工作:
$x = '31497230840470473074370324734723042.9';
bcscale(100);
var_dump(bcFloor($x));
var_dump(bcCeil($x));
var_dump(bcRound($x));
function bcFloor($x)
{
$result = bcmul($x, '1', 0);
if ((bccomp($result, '0', 0) == -1) && bccomp($x, $result, 1))
$result = bcsub($result, 1, 0);
return $result;
}
function bcCeil($x)
{
$floor = bcFloor($x);
return bcadd($floor, ceil(bcsub($x, $floor)), 0);
}
function bcRound($x)
{
$floor = bcFloor($x);
return bcadd($floor, round(bcsub($x, $floor)), 0);
}
基本上,它是通过以零精度乘以一来找到浮点数的.
Basically it finds the flooy by multiplying by one with zero precision.
然后,它可以通过从总数中减去该值来进行ceil/四舍五入,调用内置函数,然后将结果加回去
Then it can do ceil / round by subtracting that from the total, calling the built in functions, then adding the result back on
固定用于-ve数字
这篇关于如何在PHP中四舍五入/限制/下底bcmath数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文