Parse Float


Ran into a nasty behavior in an inherited codebase at one former job. Shortly after my team started, users mentioned that certain items in the database were incorrectly priced at $1.

It turns out that a previous developer had implemented some custom logic to parse a dollar amount from a popup form field.

It trimmed the "$" (which would haved caused a NaN and been noticed immediately), but it failed to remove the ",", which caused truncation.

Because values over $1,000 were rare in this system (but really important!) and the destination was a screen full of other numbers in a huge application, it took months before somebody with sharp eyes caught the bug in action.

Once we could replicate the behavior, it was easy to track down the offending line of code: an unassuming parseFloat()

I find the following javascript behavior a bit surprising:

parseFloat(1000);    // 1000, ok
parseFloat("1000");  // 1000, ok
parseFloat("1,000"); // 1, uh oh!

Sure, there are different conventions for the thousands-separator, but truncating doesn't feel like a great solution.

In fact, having personally encountered this bug several times in the wild (and probably screwing it up myself a few times too), I suspect that comma-truncated float parsing costs companies millions of dollars a year.