1

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?

Jon B
  • 497
  • 1
  • 9
  • 25
  • Working with floats does stuff like this – John Conde Apr 06 '15 at 20:48
  • 1
    Actually, i can't recreate this? – sinisake Apr 06 '15 at 20:52
  • var_dump(floatval($str)); => float 81.7704 ? – sinisake Apr 06 '15 at 20:58
  • 1
    i'll update my question with my actual code. not sure if it would matter, but the value is a property of an object that eventually gets json encoded – Jon B Apr 06 '15 at 21:00
  • See the big red warning on [this page](http://php.net/manual/en/language.types.float.php) – Jeff Lambert Apr 06 '15 at 21:14
  • thanks @watcher . that definitely is applicable. that makes this feel flawed. is there no workaround? it's not the end of the world that i use number_format or round instead and just end up with a string, but i can't help but to think there's a way around... – Jon B Apr 06 '15 at 21:41

0 Answers0