PHP轮到整数 [英] PHP round to integer
问题描述
$ b $ $ $ p $ $ c $ $ $ key =(int)round($ number)
但是,我不确定这是否会始终有效。据我所知(int)
只是截断任何小数,因为 round($ number)
返回理论上的浮点数有限的精度,有可能是 round($ number)
返回类似于7.999999 ...然后 $ key
是7而不是8?
如果这个问题确实存在(我不知道该如何测试),那该如何解决呢?也许:
$ b $ pre $ $ c $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b
有没有比这更好的解决方案?
要正确地舍入浮点数,可以使用:
ceil($ number)
:四舍五入
round($ number,0)
floor($ number)
:舍入
这些函数返回float,但是来自 Niet the Dark Absol评论: em>存储在浮点数中的整数总是精确的,高达2 ^ 51左右,这是很多无论如何都可以存储在一个int中。
I want to round a number and I need a proper integer because I want to use it as an array key. The first "solution" that comes to mind is:
$key = (int)round($number)
However, I am unsure if this will always work. As far as I know (int)
just truncates any decimals and since round($number)
returns a float with theoretically limited precision, is it possible that round($number)
returns something like 7.999999... and then $key
is 7 instead of 8?
If this problem actually exists (I don't know how to test for it), how can it be solved? Maybe:
$key = (int)(round($number) + 0.0000000000000000001) // number of zeros chosen arbitrarily
Is there a better solution than this?
To round floats properly, you can use:
ceil($number)
: round upround($number, 0)
: round to the nearest integerfloor($number)
: round down
Those functions return float, but from Niet the Dark Absol comment: "Integers stored within floats are always accurate, up to around 2^51, which is much more than can be stored in an int anyway."
这篇关于PHP轮到整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!