Why does casting a decimal string as float change the value by a fraction of the last decimal place?
For example, I have:
class API_something{
public function __construct($id, $name, $rank, $weight){
$this->id = (int)$id;
$this->name = strtolower($name);
$this->rank = (int)$rank;
$this->weight = floatval($weight);
}
}
this object gets instantiated with a string passed to $weight
. this is ultimately json_encode
'd and values are as such:
{
"weight": 81.770399999999995,
"id": 6,
"rank": 1,
"name": "ommitted"
}
I know I can use number_format
or round
to get it back to 4 decimal places, but both functions return a string.
Is there not a way to convert the original string to a float variable without PHP changing the value?