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 函數造成浮點類型數據出現精度問題

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章