数字之和返回奇数低位小数?

时间:2012-04-12 07:29:56

标签: php

当总结一组数字时,有时我会得到一些低小数?当数字被解析为字符串时,为什么会发生这种情况?我知道有一些“&!about floats

function parse(){
    foreach($_SESSION['import_csv_posts']['result']['csv'] as $key => $post){
        $amount = $this->parse_amount($post[$this->param['amount']]);
        if($this->param['vat_amount']){
            $amount += $this->parse_amount($post[$this->param['vat_amount']]);
        }

        $this->balance += $amount;
        echo "$amount\n";
    }

    echo "\nbalance = ".$this->balance;
}

function parse_amount($amount){
    $amount = strval($amount);
    if(strstr($amount, '.') && strstr($amount, ',')){
        preg_match('/^\-?\d+([\.,]{1})/', $amount, $match);
        $amount = str_replace($match[1], '', $amount);
    }

    return str_replace(',', '.', $amount);
}

结果

-87329.00
-257700.00
-11400.00
-9120.00
-47485.00
-15504.00
122800.00
1836.00
1254.00
200.00
360.00
31680.00
361.60
1979.20
1144.00
7520.00
6249.49
balance = -399.00000000003

2 个答案:

答案 0 :(得分:3)

“%”&!关于浮动“是浮动只是不精确。在有限空间中存储无限数字存在一定的不准确性。因此,在使用浮点数进行数学运算时,您将无法获得100%准确的结果

您的选择是在输出时将format numbers舍入到小数点后两位,或者使用字符串和BC Math package,这是较慢但准确的。

答案 1 :(得分:1)

浮点运算由计算机以二进制方式完成,而结果以十进制显示。有许多数字在两个系统中都无法同样精确地表示,因此,作为人类期望结果的结果与作为比特看到的实际结果之间几乎总是存在一些差异(这就是你不能的原因)可靠地比较浮点数是否相等)。

通过解析字符串生成数字并不重要,只要PHP看到算术运算符,它就会在内部将字符串转换为数字。

如果你没有要求绝对精度(看起来你没有,因为你只是显示东西),那么只需使用printf格式字符串,例如{{1限制小数位数。

相关问题