ben tedder : code things

Rounding errors when unit testing math in React with Jest

I'm writing a function that mirrors some basic math that is being done in a Google Sheet document. Something like this:

employee 1  |  $10
employee 2  |  $15
employee 3  |  $10

The Google Sheet formula looks like this:

(A1+A2+A3) / 3

You'd expect the formula to be doing 35 / 3. And therein lies the problem. My formula was rounded and showed $11.67. That number is very different than the true number, $11.66666666666670.

Now what does this have to do with React and Jest? This averaging functionality was being replicated to serve a UI that has the same purpose, to average the wages of {n} employees.

For the sake of simplicity I'll spare you the extra functions that served this method, as they did things like add markup percentages, hourly overtime, etc. But it's important, because they also were doing math.

So like a good developer (I joke) I started with a unit test in Jest.

expect(avgHourlyRate).toEqual(expectedRate);

This kept failing:

expect(received).toEqual(expected)
Expected value to equal:
  17.5
Received:
  17.499999999999996

In looking at the Docs for what to 'expect' in Jest I stumbled upon the toBeCloseTo. I loved this line in the docs:

It fails because in JavaScript, 0.2 + 0.1 is actually 0.30000000000000004. Sorry.

expect(avgHourlyRate).toBeCloseTo(expectedRate);

What a comforting feeling that leaves you with.

Javascript is awesome.