1
ini_set('precision', 32);

var_dump(0.855);
//float(0.84999999999999997779553950749687)

var_dump(round(0.855, 2, PHP_ROUND_HALF_EVEN));
//float(0.85999999999999998667732370449812)

var_dump((float)sprintf('%.2f', 0.855));
//float(0.84999999999999997779553950749687)

Why is there a difference between the results for sprinf() and round()?

I understand 0.855 cannot be represented as an exact number in IEEE754, this is not a question about why that is occuring.

This answer indicates C like functions apply “round to nearest and ties to even” which is what I would expect the PHP_ROUND_HALF_EVEN flag should replicate.

Edit: I don't want to fight the [duplicate] closure so if anyone finds this in future and is interested, the closest answer in the linked questions is https://stackoverflow.com/a/27108849/820841 which states round() is written to “do the right thing”. I suppose this shall have to satisfy my curiosity for now.

chris
  • 3,019
  • 23
  • 21
  • cf. http://php.net/sprintf, description of the `format` parameter, section `precision specifier` (5th item in the list). – Dormilich Apr 18 '18 at 12:03

0 Answers0