Calculation precision in JavaScript

Has there been any progress in fixing the problem with imprecise calculations in JavaScript (e.g. 0.1+0.2===0.3 returns false)?

I’ve expressed my disappointment on numerous occasions before about this problem and have just been hit again when using MongoDB’s $divide aggregation operator. 280/0.28 returns 999.9999... when I need it to return 1000 for correct sort order.

In my own code I use https://www.npmjs.com/package/big-number for precise calculations but I have no control over how MongoDB does $divide, so it’s very frustrating.

This is because JavaScript uses the IEEE-754 64-bit specification for floating point. MongoDB themselves have some advice on maintaining precision:

https://docs.mongodb.com/manual/tutorial/model-monetary-data/

Note that you’ll need to do calculations with the database engine, not JS code to take advantage of NumberDecimal.

3 Likes

NumberDecimal was released in MongoDB 3.4, and looks like I could use it for accurate aggregation queries.
Though I can’t use Meteor’s built-in MongoDB to try it as it’s still at version 3.2.15.

1 Like

0.1+0.2===0.3 is false

That’s pretty much a standard issue for any and all languages using floats.

1 Like

Not for a long time (e.g. decade) in Java, ASP.NET, etc. I’ve already expressed my thoughts before which you can read in these threads:

1 Like

Erm, no. In Java you need to do java.lang.Float.compare(float1, float2) for example. The problem is inherent to floats.

Either you use other data types or you create special functions (for example using an error margin, though that has problems of its own).

Again: This is an inherent problem of the data type which makes naive comparison through a standard implementation of == impossible.

It’s why the data type decimal(aka numeric) exists in the first place.

I meant that the BigDecimal data type was provided in Java around a decade ago. Nobody should still be using other data types for monetary data and calculations in Java.

What has been done in JavaScript for the same problem? ECMA have been busy giving us a whole lot of programming shorthand (ES6 or ES2015). But will they do anything about making it easier to do accurate monetary calculations? Or are they still spending their time and effort to give us more exciting shorthand coding syntax so that one day we’ll be able to write full-featured infinitely-scalable production-ready apps in around 10 lines of code?

Maybe, just maybe, Javascript isn’t the proper language for financial applications then?

I mean, I wouldn’t trust a weakly-typed language anyway for anything really important…

1 Like