PHP Displays weird rounding errors when doing math on a string input.
12 comments · 17% upvoted · source · other discussions
12 comments · 17% upvoted · source · other discussions
Doing math on strings sounds wrong.
Funnily enough it's one of the most common way to do arbitrary precision math in php via bcmath (the other common way is gmp, which I think uses a c library in and exposes the data only via accessor functions)
I think the fact that it is stored as a string should be an implementation detail. A nice API wouldn't expose the string, but expose an object to be passed around.
It operates on strings because it's a library originally made for a command-line calculator (bc, hence the name bcmath).
That's not at all related to strings, but this is just a side-effect of the fact that many floating point values can't be represented accurately. This is a property of most programming languages out there.
Yes. It sucks. But considering that next to every language does this, I don't think it warrants a posting here.
Here are exmpales in C, C#, Java, Swift, Ruby and Python.
tdammers 13 points · Aug 2016
The difference between PHP and all those other languages there is that PHP is the only one where making sure you're not accidentally using floats is difficult.
pilif 13 points · Aug 2016
PHP is the only language where making sure you're not accidentally using any scalar data type is difficult.
cfreak2399 6 points · Aug 2016
I think the mods need to put something in the side-bar about this because its getting a bit ridiculous. We have a post about once a month that is lolfloatingpoint not lolphp.
DoctorWaluigiTime 3 points · Aug 2016
Not to mention the series of posts that are "lolbadprogramming" instead of lolphp.
kafoso 5 points · Aug 2016
Indeed. This will happen on all 32 or 64 bit systems in most (if not all?) programming languages.
/u/c12
Javascript example to get your gray hairs started: https://jsfiddle.net/wy8rqeer/