我只是使用 PHP Laravel 作為 API 來簡單地增加浮點(diǎn)數(shù),如下面的代碼;代碼:public function testArrIncrement(){ $arr["test"]["words"] = "The quick brown fox jumps over a lazy dog"; $arr["test"]["number"] = 0; for($i=0; $i<11; $i++) $arr["test"]["number"] += 0.01; return response()->json($arr, 200);}結(jié)果:{ "test": { "words": "The quick brown fox jumps over a lazy dog", "number": 0.10999999999999999 }}奇怪的是,為什么 $arr["test"]["number"] 的值不是 0.11,而是 0.10999999999999999?但是,如果我只使用沒有任何框架的普通單文件 PHP 嘗試相同的代碼,則一切正常 $arr["test"]["number"] 的值確實(shí)是 0.11。代碼:$arr["test"]["words"] = "The quick brown fox jumps over a lazy dog";$arr["test"]["number"] = 0;for($i=0; $i<11; $i++) $arr["test"]["number"] += 0.01;var_dump($arr);結(jié)果:array(1) { ["test"]=> array(2) { ["words"]=> string(41) "The quick brown fox jumps over a lazy dog" ["number"]=> float(0.11) } }請幫忙為什么會這樣??
1 回答

qq_笑_17
TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超7個贊
這是由于數(shù)據(jù)被編碼成json。如果您嘗試,json_encode您將遇到預(yù)期的相同行為。php.ini您必須像這樣在代碼中或代碼中設(shè)置精度:
public function testArrIncrement(){
ini_set('serialize_precision', 14);
$arr["test"]["words"] = "The quick brown fox jumps over a lazy dog";
$arr["test"]["number"] = 0;
for($i=0; $i<11; $i++) $arr["test"]["number"] += 0.01;
return response()->json($arr, 200);
}
- 1 回答
- 0 關(guān)注
- 106 瀏覽
添加回答
舉報
0/150
提交
取消