2012-04-12 39 views
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 
+0

什么是“低位小数”? – deceze 2012-04-12 07:31:43

+1

好吧,原谅我的无知,但我没有看到你在哪里解析字符串以获得浮点值? – Adi 2012-04-12 07:38:26

+0

@adnan使用'+ ='时自动发生。 – deceze 2012-04-12 07:43:13

回答

3

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

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

1

浮点运算由计算机以二进制完成,而结果以十进制显示。在这两个系统中有很多数字不能同等精确地表示,因此,作为人类期望的结果与以位表示的实际结果几乎总是有区别的(这是因为你不能可靠地比较花车的平等)。

无论您的数字是通过解析字符串生成的,只要PHP看到算术运算符,它会在内部将字符串转换为数字。

如果不要求绝对精度(它看起来像你不这样做,因为你只是显示的东西),然后只需使用printf与格式字符串如%.2f限制小数位的数量。