PHP: rounding a number

Hey. I have the problem of rounding numbers to -0 , not just 0

the code:

<?php $num= 0.000000031; $round = number_format((float)$num, 1, '.', ''); echo $round * -1; ?> 

Output: -0

expected result: 0

I searched for any solution but found nothing.

kindly explain and help me why is it rounded to -0 instead of 0 ? thanks

+8
floating-point php rounding
source share
3 answers

Not rounding does -0.

The $ round variable contains this before the last line:

 string(3) "0.0" 

You can verify this by adding this line:

 var_dump($round); 

before the echo.

So, if you multiply "0.0" (string) by -1, then the result will be "-0"

Because (string) 0 is cast to (float) 0 before multiplication and

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

This is a completely normal value based on the behavior of floating numbers. (More: 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) 
+6
source share

You, PHP, deform it.

I assume that var $ xx on the second line is $ num.

Then you must first perform all operations (working level), and then make presentations (presentation level):

 <?php // Operation layer $num = 0.000000031; $round = $num * -1; // Presentation layer echo number_format($round, 1, '.', ''); 

When you do number_format, extract the string, not the number.

0
source share

Since number_format returns a string, you need to give it away to get the expected result.

 <?php $num= 0.000000031; $round = number_format((float)$num, 1, '.', ''); echo (int)$round * (-1); //print 0 ?> 

PHP Sandbox

0
source share

All Articles