简体   繁体   English

PHP:number_format舍入

[英]PHP: number_format rounding

Hi I've been having a problem rounding numbers to -0 instead of just a 0 嗨,我一直有一个问题将数字四舍五入到-0而不是一个0

code: 码:

<?php
$num= 0.000000031;

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

echo $round * -1;
?>

output: -0 输出: -0

expected output: 0 预期产量: 0

I've been looking to any solution but nothing found. 我一直在寻找任何解决方案,但没有找到。

kindly explain & help me why it rounds up to -0 instead of 0 ? 亲切地解释并帮助我为什么它会向上舍入-0而不是0 thank you 谢谢

Not the rounding makes it -0. 舍入不是-0。

The $round variable contains this before the last line: $ round变量在最后一行之前包含这个:

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" 因此,如果将“0.0”(字符串)乘以-1,则结果将为“-0”

Because (string)0 is casted to (float)0 before the multiplication and 因为(字符串)0在乘法和之前被转换为(float)0

(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 ) (更多细节: http//en.wikipedia.org/wiki/Signed_zero

If this is a problem you can add 0 to avoid this "magic": 如果这是一个问题,你可以添加0以​​避免这种“魔术”:

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

You PHP code it's disorganized. 你PHP代码它没有组织。

I assume the var $xx on the second line it's $num. 我假设第二行的var $ xx是$ 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. 当你执行number_format检索字符串而不是数字时。

Since number_format returns string, you need to cast it to get expected result. 由于number_format返回字符串,因此需要将其强制转换以获得预期结果。

<?php

$num= 0.000000031;

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

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

?>

PHP Sandbox PHP沙盒

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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