PHP Displays weird rounding errors when doing math on a string input.

12 comments · 17% upvoted · source · other discussions

comments

pilif

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

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

PHP is the only language where making sure you're not accidentally using any scalar data type is difficult.

cfreak2399

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

Not to mention the series of posts that are "lolbadprogramming" instead of lolphp.

kafoso

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/

[deleted]

Doing math on strings sounds wrong.

mythril

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)

[deleted]

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.

mythril

:) whenever I use it I wrap access in an object, shouldn't have to though, I agree.

[deleted]

I guess we can say PHP is pretty low level, which is kind of cool. It makes it more fun to create abstractions around the "low level" functions that are wrapping a C api.

the_alias_of_andrea

It operates on strings because it's a library originally made for a command-line calculator (bc, hence the name bcmath).