You Old Fool
You Old Fool

Reputation: 22941

Why does setting 'precision' break php round()?

Recently came across a situation where I was working on a server that had a php.ini file with:

precision = 16

The default being 14, this seems harmless enough. Unfortunately it lead to this:

// ini_set('precision', 16);
echo round((20.12 / 36.79),4);

Result: 0.5469000000000001

Huh? Shouldn't round() be taking care of the floating point precision issues here?

Upvotes: 2

Views: 780

Answers (1)

zerkms
zerkms

Reputation: 254926

php's round() function still returns a floating point number, not a string, so it might be inexact.

0.5469 is presented as the following 8 bytes 0x3FE180346DC5D639 encoded double precision IEEE754.

Which is not the exact representation of 0.5469 but a closest representible number, which actually is 5.46900000000000052757798130187E-1

References:

Upvotes: 1

Related Questions