As far as programming goes, I spend more time — at least lately — debating what new things to learn rather than actually learning new things. And I generally haven’t gone about these debates in a systematic manner. I mostly go to Google and type some variant of “should i learn haskell or go” and skim through some blog posts and Reddit threads and then I do something unrelated for a couple hours while I worry about future proofing my skills and then I return to Google and type in the same phrase and click on the same links.

Recently, I’ve been scheming various side projects that involve many calculations. JavaScript, which is generally the first language I consider for any project, has a bad reputation with math. If you Google “javascript math bad,” you’ll find examples like what I’ve written below (similar to this blog post):

const price = 1.2;
const quantity = 3;
const total = price * quantity;

// Outputs 3.5999999999999996
// instead of 3.6

It may be that JavaScript is a relatively poor choice for applications where mathematical accuracy matters, but the core problem demonstrated above could appear in any language. As described pretty well on this website, the problem is that floating point numbers can’t precisely represent decimals.

I can demonstrate the same problem in Python. If I go to my command line and type python to open a REPL, I can naively yield:

>>> x = 0.1
>>> y = 0.2
>>> x + y

While on a Hacker News thread about ReasonML, I saw someone comment:

BTW does Reason offer a solution for decimal the decimal precision problem there is in JavaScript?

ReasonML does not. It has integer and float types, and the fact that we use float types to represent decimals is the source of our collective confusion. I replicated my JavaScript example above in a ReasonML project:

let price = 1.2;
let quantity = 3.0;
let total = price *. quantity;


And the generated JavaScript still logged 3.5999999999999996:

'use strict';

var total = 1.2 * 3.0;


var price = 1.2;

var quantity = 3.0;

exports.price = price;
exports.quantity = quantity; = total;
/*  Not a pure module */

I haven’t found a great guide to dealing with math in JavaScript. There are a number of libraries for mathematical and financial operations, but it doesn’t seem like there’s a dominant solution. I also haven’t seen something like a, “CSS Tricks Guide to Flexbox” for math in JavaScript.