PHP round to integer

天大地大妈咪最大 提交于 2020-01-29 10:19:32

问题


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?


回答1:


To round floats properly, you can use:

  • ceil($number): round up
  • round($number, 0): round to the nearest integer
  • floor($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."




回答2:


round(), without a precision set always rounds to the nearest whole number. By default, round rounds to zero decimal places.

So:

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

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

So, if your goal is to use this as a key for an array, this should be fine.

You can, of course, use modes and precision to specify exactly how you want round() to behave. See this.

UPDATE

You might actually be more interested in intval:

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



回答3:


Integers stored within floats are always accurate, up to around 253, which is much more than can be stored in an int anyway. I am worrying over nothing.




回答4:


What about simply adding 1/2 before casting to an int?

eg:

$int = (int) ($float + 0.5);

This should give a predictable result.




回答5:


Round to the nearest integer

$key = round($number, 0);



来源:https://stackoverflow.com/questions/38746283/php-round-to-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!