How to ceil a number to 13 decimals in JavaScript

The Easy Way

A common use-case of our beloved front-end language, JavaScript, is to ceil a given number. In this short tutorial we will explore how to do this exactly, in an easy yet keeping the precision.

Imagine we fetch the number below from an API, whether it is first- or third-party is not important in this case.

In this case we have gotten the number above, which has 15 decimals, but as we very much love to better the user-experience (UX), and actually make the number more understandable, we would like to ceil to 13 decimals instead.

Hick-ups

Yes, it is actually that easy! Although, sometimes we don't care if the number does up or down, thus using the Math.round()-function is quite handy as well. We could simply switch the ceil for our beloved round, alas, sadly with some numbers, we end up rounding wrong this is not something we will go into details with, but you can read more here if you are curious.

The TL;DR is that you can simply add Epsilon to the original number, before we do anything else with it. The snippet is written as below.

In our case it doesn't matter as we ceil, but if you read through the stack-overflow question from earlier, you will get some ideas on when and why to use it. Always remember though, JavaScript can be a funny thing to mess with.