0

当对一组数字求和时,有时我会得到一些低位小数?为什么将数字解析为字符串时会发生这种情况?我知道有一些 %"&! 关于浮动

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
4

2 回答 2

3

这 ”%”&!关于浮点数”是浮点数根本不精确。无限数如何存储在有限空间中存在一定的不准确性。因此,在使用浮点数进行数学运算时,您不会得到 100% 准确的结果。

您的选择是在输出时将数字四舍五入,格式化为小数点后两位,或者使用字符串和BC Math 包,它速度较慢,但​​准确。

于 2012-04-12T07:40:04.487 回答
1

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

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

如果您不需要绝对精度(看起来您不需要,因为您只是在显示内容),那么只需使用printf格式字符串%.2f来限制小数位数。

于 2012-04-12T07:45:26.653 回答