3

Take the following code:

echo round(1215.49999);

The answer I get, is 1215, which is what I want.

However, when you write this:

echo round(1215.499999999999999);

The answer I get is 1216.

Is there any particular reason for this? I would like to end up with 1215 in both cases.

ThePerplexedOne
  • 2,920
  • 15
  • 30

2 Answers2

1

If you wanted to use built-in PHP functions as opposed to writing your own, you could use bcdiv.

You will need to have bcmath enabled in your php.ini file to use bcmath functions, this may already be enabled, but if not it should just be a case of including the following:

--enable-bcmath

Example 1:

echo bcdiv(1215.49999, 1, 2);

Example 2:

echo bcdiv(1215.499999999999999, 1, 2);

Both of the above examples will output 1215.

Sources:

Source 1

Source 2

Source 3

Community
  • 1
  • 1
Mark
  • 1,852
  • 3
  • 18
  • 31
1

If the input 1215.499999999999999 is interpreted from php as a float, everything is too late to round. This number is then identical to 1215.5

a test:

var_dump(1215.499999999999999 === 1215.5); //bool(true)

If the input is to be rounded , bcmat must be used and the input as string.

$input = '1215.499999999999999';
echo bcadd($input,0.5,0);  //1215

$input = '1215.5000000000000000';
echo bcadd($input,0.5,0);  //1216
jspit
  • 7,276
  • 1
  • 9
  • 17