PHP number_format() and a problem with negative values rounded to zero

Want to support HowtoForge? Become a subscriber!
 
Submitted by Croydon (Contact Author) (Forums) on Wed, 2014-04-09 09:18. :: PHP

PHP number_format() and a problem with negative values rounded to zero

As is known, the PHP function number_format() rounds the given value to the needed amount of decimal places.

E. g.:
$a = 2.658;
$x = number_format($a, 2); // --> 2.66
$x = number_format($a, 0); // --> 3

From my point of view, there is a poor side-effect when using negative numbers that should be round to 0 (zero).

E. g.:
$a = -0.00000003;
$x = number_format($a, 2); // --> -0.00
$x = number_format($a, 0); // --> -0

You see the minus sign in front of the output? This is espacially annoying when it occurs because of inaccuracy of the internal floating point operations inside PHP.

E. g.:
$a = 7.8;
$b = 7.79;
$c = 0.01;
$result = $a - $b - $c;
$x = number_format($result, 2); // --> -0.00

In this case the minus sign (-0.00) is a result of the fact, that the result is -0.00000000000000021337 due to floating point inaccuracy. However the result varies due to the settings of php.ini and the php version. In my tests I used PHP 5.3 with a floating point accuracy of 13 decimal places.

You can avoid this behaviour of number_format() easily by rounding the value to the needed decimal places just before passing it to the function.

E. g.:
$a = -0.00000003;
$x = number_format(round($a, 2), 2); // --> 0.00
$x = number_format(round($a, 0), 0); // --> 0


Please do not use the comment function to ask for help! If you need help, please use our forum.
Comments will be published after administrator approval.