nickf
nickf

Reputation: 546025

How to deal with strange rounding of floats in PHP

As we all know, floating point arithmetic is not always completely accurate, but how do you deal with its inconsistencies?

As an example, in PHP 5.2.9: (this doesn't happen in 5.3)

echo round(14.99225, 4);  // 14.9923 
echo round(15.99225, 4);  // 15.9923 
echo round(16.99225, 4);  // 16.9922 ??
echo round(17.99225, 4);  // 17.9922 ??
echo round(25.99225, 4);  // 25.9922 ??
echo round(26.99225, 4);  // 26.9923

How would you work around this?

Upvotes: 8

Views: 2135

Answers (2)

Michael Borgwardt
Michael Borgwardt

Reputation: 346260

how do you deal with its inconsistencies?

  • For stuff where exact results based on decimal representation matters (i.e. money), do not use IEEE754 floats, you use "bignum" libraries like BCMath
  • For stuff where you just need your calculations to be relatively precise (like most scientific calculations), you use numerically stable algorithms so that the inconsistencies stay in the least significant bits (where they don't matter).

Upvotes: 4

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798566

Welcome to IEEE754, enjoy your stay.

Use bc or gmp instead.

Upvotes: 8

Related Questions