简体   繁体   中英

PHP: number_format rounding

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

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)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM