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?
Advertisement
Answer
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.”