为什么显示到多个小数位?

问题描述 投票:0回答:1

为什么当我将$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 }]
php
1个回答
1
投票

这是浮点精度的问题。请参阅https://www.php.net/manual/en/language.types.float.php处的警告>

从链接中突出显示:

© www.soinside.com 2019 - 2024. All rights reserved.