为什么当我将$artWidthCM
和$artHeightCM
添加到对象时,为什么不对它进行四舍五入?
如果回显值,我将得到预期的:'0.305'。
但是将其添加到$artObj
时,其打印为'0.304999999999999993393338661852249060757458209991455078125'。
if ($result->num_rows > 0) {
$artObj = new stdClass();
while($row = $result->fetch_assoc()) {
//Dimensions
$dimenionsStrip = str_replace(' ', '', $row["Dimensions"]);
$dimensionsArr = explode("x", $dimenionsStrip);
$artWidthInch = 12; // $dimensionsArr[0];
$artHeightInch = 12; // $dimensionsArr[1];
$artWidthCM = (round(($artWidthInch * 2.54) * 2) / 2) / 100;
$artHeightCM = (round(($artHeightInch * 2.54) * 2) / 2) / 100;
// Build Object
$artObj->id = $row["ArtID"];
$artObj->artwidth = $artWidthCM;
$artObj->artheight = $artHeightCM;
}
$artJSON = json_encode($artObj, JSON_PRETTY_PRINT);
echo '['.$artJSON.']';
} else {
echo "No Artwork Found";
}
如下打印JSON:
[{ "id": "35628", "artwidth": 0.304999999999999993338661852249060757458209991455078125, "artheight": 0.304999999999999993338661852249060757458209991455078125 }]
在我的本地计算机上,其完全相同的代码打印为:
[{ "id": "35628", "artwidth": 0.305, "artheight": 0.305 }]
这是浮点精度的问题。请参阅https://www.php.net/manual/en/language.types.float.php处的警告>
从链接中突出显示: