为什么显示为小数点后几位

  • 本文关键字:几位 显示 小数点 php
  • 更新时间 :
  • 英文 :


当我将$artWidthCM$artHeightCM添加到对象时,为什么不保持其舍入?

如果我回显这些值,我会得到预期值:0.305。

但当将其添加到$artObj时,它打印为"0.3049999999999993338661852249060757458209991455078125"。

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

链接亮点:

所以永远不要相信浮点数的结果是最后一位,也不要直接比较浮点数是否相等。如果更高精度是必要的,任意精度的数学函数和gmp功能可用。

浮点处理在不同的机器上可能不同,这就是为什么它在一台机器上表现"正确",在另一台机器中表现"不正确"。

最新更新