Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP round to integer

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?

like image 791
AndreKR Avatar asked Aug 03 '16 14:08

AndreKR


People also ask

How do I round to 2 decimal places in PHP?

Example #1 round() examples php echo round(3.4); // 3 echo round(3.5); // 4 echo round(3.6); // 4 echo round(3.6, 0); // 4 echo round(1.95583, 2); // 1.96 echo round(1241757, -3); // 1242000 echo round(5.045, 2); // 5.05 echo round(5.055, 2); // 5.06 ?>

How do you round to integer?

Rounding to the Nearest Integer If the digit in the tenths place is less than 5, then round down, which means the units digit remains the same; if the digit in the tenths place is 5 or greater, then round up, which means you should increase the unit digit by one.

What is a PHP round?

The round() function in PHP is used to round a floating-point number. It can be used to define a specific precision value which rounds number according to that precision value. Precision can be also negative or zero.

What is ceil and floor in PHP?

Both ceil() and floor() take just one parameter - the number to round. Ceil() takes the number and rounds it to the nearest integer above its current value, whereas floor() rounds it to the nearest integer below its current value.


2 Answers

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."

like image 199
Mistalis Avatar answered Oct 19 '22 16:10

Mistalis


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
like image 7
Zac Brown Avatar answered Oct 19 '22 15:10

Zac Brown