0

Why is this not keeping the rounding on the $artWidthCM and $artHeightCM when I am adding it to the object?

If I echo out the values I get what is expected: '0.305'.

But when adding it to $artObj it prints as '0.304999999999999993338661852249060757458209991455078125'.

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";
}

Prints JSON as follows:

[{ "id": "35628", "artwidth": 0.304999999999999993338661852249060757458209991455078125, "artheight": 0.304999999999999993338661852249060757458209991455078125 }]

On my local machine with exact same code it prints as:

[{ "id": "35628", "artwidth": 0.305, "artheight": 0.305 }]
cnrhgn
  • 703
  • 4
  • 18

1 Answers1

1

This is a problem of floating point precision. See the Warning at https://www.php.net/manual/en/language.types.float.php

Highlight from the link:

So never trust floating number results to the last digit, and do not compare floating point numbers directly for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

The floating point handling may be different on different machines, that's why it behaves "correctly" on one and "incorrectly" on other.

Filip Halaxa
  • 728
  • 6
  • 13
  • I think his question is more about why `echo` is automatically rounding this value while `json_encode` is not. Obviously, the floating point value can never really be trusted. However, it shouldn't change from statement to statement. – Sturm Apr 30 '20 at 15:50
  • Or why it's getting rounded when printed from the terminal but not as a json response, perhaps. – Sturm Apr 30 '20 at 15:51
  • I understand that the question is about different behaviour on different systems. I added it to the answer. – Filip Halaxa Apr 30 '20 at 15:54
  • I had assumed that this was all being done on the same machine, probably my mistake. – Sturm Apr 30 '20 at 16:18