Home » Php » floating point – PHP: number_format rounding

floating point – PHP: number_format rounding

Posted by: admin July 12, 2020 Leave a comment

Questions:

Hi I’ve been having a problem rounding numbers to -0 instead of just a 0

code:

<?php
$num= 0.000000031;

$round = number_format((float)$num, 1, '.', '');

echo $round * -1;
?>

output:
-0

expected output:
0

I’ve been looking to any solution but nothing found.

kindly explain & help me why it rounds up to -0 instead of 0? thank you

How to&Answers:

Not the rounding makes it -0.

The $round variable contains this before the last line:

string(3) "0.0"

You can verify this with adding this line:

var_dump($round);

before the echo.

So if you multiply “0.0” (string) with -1 then the result will be “-0”

Because (string)0 is casted to (float)0 before the multiplication and

(float)0 * -1 = -0

php5 -r 'var_dump((float)0*-1);'
float(-0)

Which is completely normal based on the floating numbers behaviour. (More details: http://en.wikipedia.org/wiki/Signed_zero )

If this is a problem you can add 0 to avoid this “magic”:

php5 -r 'var_dump((float)0*-1+0);'
float(0)

Answer:

Since number_format returns string, you need to cast it to get expected result.

<?php

$num= 0.000000031;

$round = number_format((float)$num, 1, '.', '');

echo (int)$round * (-1);  //print 0 

?>

PHP Sandbox

Answer:

You PHP code it’s disorganized.

I assume the var $xx on the second line it’s $num.

Then, you must first do all operations (operation layer) and then do presentations (presentation layer):

<?php
    // Operation layer
    $num = 0.000000031;
    $round = $num * -1;

    // Presentation layer
    echo number_format($round, 1, '.', '');

When you do a number_format retrieve a string, not a number.