Reputation: 703
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 }]
Upvotes: 0
Views: 47
Reputation: 778
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.
Upvotes: 1