天天看點

php7.1 round、json_encode 精度不準确問題/浮點類型資料出現精度問題 解決方案

一.round

項目中使用round(xx, 2)後精度有問題,出現并沒有四舍五入到小數點後2位。

谷歌很長時間,終于找到解決辦法。

在php.ini中設定serialize_precision = -1 即可 

轉自:php7.1使用round後精度不準确問題解決方案

二.json_encode

新項目用的 php 

7.1.13

 版本,在使用過程中發現 

浮點類型

 資料經過 

json_encode

 之後會出現精度問題。

舉個例子:

$data = [
    'stock' => '100',
	'amount' => 10,
    'price' => 0.1
];

var_dump($data);

echo json_encode($data);
           

輸出結果:

array(3) { 
    ["stock"]=> string(3) "100" 
    ["amount"]=> int(10) 
    ["price"]=> float(0.1) 
}

{
    "stock":"100",
    "amount":10,
    "price":0.10000000000000001
}
           

網上說可以通過調整 

php.ini

 中 

serialize_precision (序列化精度)

 的大小來解決這個問題。

; When floats & doubles are serialized store serialize_precision significant
; digits after the floating point. The default value ensures that when floats
; are decoded with unserialize, the data will remain the same.
; The value is also used for json_encode when encoding double values.
; If -1 is used, then dtoa mode 0 is used which automatically select the best
; precision.
serialize_precision = 17
           

按照說明,将這個值改為 

小于 17

 的數字就解決了這個問題。

後來又發現一個折中的辦法,就是将 

float

 轉為 

string

 類型。

$data = [
	'stock' => '100',
	'amount' => 10,
    'price' => (string)0.1
];

var_dump($data);

echo json_encode($data);
           

輸出結果:

array(3) { 
    ["stock"]=> string(3) "100" 
    ["amount"]=> int(10) 
    ["price"]=> string(3) "0.1" 
    
} 

{
    "stock":"100",
    "amount":10,
    "price":"0.1"
}
           

這樣子也解決了問題,但是總感覺不太友善,是以就有了這個函數。

/**
 * @param $data 需要處理的資料
 * @param int $precision 保留幾位小數
 * @return array|string
 */
function fix_number_precision($data, $precision = 2)
{
    if(is_array($data)){
        foreach ($data as $key => $value) {
            $data[$key] = fix_number_precision($value, $precision);
        }
        return $data;
    }

    if(is_numeric($data)){
        $precision = is_float($data) ? $precision : 0;
        return number_format($data, $precision, '.', '');
    }

    return $data;
}
           

測試:

$data = [
	'stock' => '100',
	'amount' => 10,
    'price' => 0.1,
    'child' => [
    	'stock' => '99999',
		'amount' => 300,
	    'price' => 11.2,
    ],
];

echo json_encode(fix_number_precision($data, 3));
           

輸出結果:

{
    "stock":"100",
    "amount":"10",
    "price":"0.100",
    "child":{
        "stock":"99999",
        "amount":"300",
        "price":"11.200"
    }
}
           

PS: php 版本 >= 7.1 均會出現此問題。

轉自:php 7.1 使用 json_encode 函數造成浮點類型資料出現精度問題