📬 blog.addEventListener()? Sign me up | No, thanks

React Ottawa: Dealing with Monetary Values

I gave a talk at the April 2019 installment of the Ottawa React meetup on the topic of “Dealing with Monetary Values in React.” I had so much fun putting together this talk; from hours spent digging through my folks’ photo archives for a picture of me working at Tim Hortons, to building a working replica of the cash register I remember from 16 years ago. The slides don’t really stand on their own so I thought I would put together a short post with links to a few resources.

Side by side: screengrab from a video of a Tim's register in use, and my demo app replica to the right

👆Side by side: screengrab from a video of a Tim’s register in use, and my demo app replica to the right.

Floating point numbers in JavaScript

While it was a React meetup and my cash register example was built with React, these principles and libraries can work in JavaScript apps of any kind: Node, web, Electron and React Native alike.

The library that I highlighted for dealing with arbitrary-precision floating point numbers is one called big.js written by GitHub user Michael M.

Why is such a library needed, you might ask? Just type 0.3-0.1 into your nearest JS console to find out. While being “off” by such a small fraction might seem insignificant, these rounding errors become compounded over a series of operations. When precision is critical, I’d recommend reaching for a library like big.js.

Why not store prices in cents?

I wrote about this in a previous post which also goes into more detail about my admiration for big.js, as well as details on using it with an SQLite database in a React Native app.

For another take on the downsides to the cents approach, check out the definitive Floating Point Guide.

Show me the code!

The cash register example I demo’d can be found here:

The app was built with a few neat pieces of tech:

Details on running the code can be found in the README, but let me know if you run into any issues.

Floating point numbers

If I piqued your interest about how floating point numbers work in computers, I would like to point you to a few resources that helped build my understanding of the topic:

  1. Floating Point Numbers - Computerphile on YouTube
  2. Floating Point Arithmetic 1: Addition - Jacob Schrum on YouTube
  3. The entire Floating-Point Guide site

Lastly, a big thanks to those that came out to the meetup, to Shopify for hosting, and to the organizers for putting together a consistently awesome event! Don’t miss Kent C. Dodds (!!) next month: meetup.com/Ottawa-ReactJS-Meetup/events/260941602/