Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 574
Lutianna Avatar asked Dec 24 '14 11:12

Lutianna


People also ask

How do I round to 2 decimal places in PHP?

Example #1 round() examples php echo round(3.4); // 3 echo round(3.5); // 4 echo round(3.6); // 4 echo round(3.6, 0); // 4 echo round(1.95583, 2); // 1.96 echo round(1241757, -3); // 1242000 echo round(5.045, 2); // 5.05 echo round(5.055, 2); // 5.06 ?>

How can I limit float to 2 decimal places in PHP?

Use number_format() Function to Show a Number to Two Decimal Places in PHP. Use round() Function to Show a Number to Two Decimal Places in PHP. Use sprintf() Function to Show a Number to Two Decimal Places in PHP.

How do you round decimals?

There are certain rules to follow when rounding a decimal number. Put simply, if the last digit is less than 5, round the previous digit down. However, if it's 5 or more than you should round the previous digit up. So, if the number you are about to round is followed by 5, 6, 7, 8, 9 round the number up.


1 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)
like image 87
Lajos Veres Avatar answered Oct 07 '22 16:10

Lajos Veres