PHP is rounded to the nearest whole

I want to round a number, and I need my own integer, because I want to use it as an array key. The first "decision" that comes to mind is:

$key = (int)round($number)

However, I'm not sure if this will always work. As far as I know, it (int)simply truncates any decimal numbers, and since it round($number)returns a float with theoretically limited precision, is it possible that it round($number)returns something like 7.999999 ... and then $keyequals 7 instead of 8?

If this problem really exists (I don’t know how to check it), how can I solve it? May be:

$key = (int)(round($number) + 0.0000000000000000001) // number of zeros chosen arbitrarily

Is there a better solution than this?

+4
source share
5 answers

:

float, Niet the Dark Absol comment:" , , , 2 ^ 51, int .

+4

round(), . .

:

$int = 8.998988776636;
round($int) //Will always be 9

$int = 8.344473773737377474;
round($int) //will always be 8

, - , .

, , , , round() . . .

UPDATE

intval:

echo intval(round(4.7)); //returns int 5
echo intval(round(4.3)); // returns int 4
0

: round, ceil (round up), floor ( ). , .

0

, , , 2 53 , int . .

0

$key = round ($ number, 0);

-1

Source: https://habr.com/ru/post/1650043/


All Articles