Sitemap
Better Programming

Advice for programmers.

The Never-Ending Story of Rounding Numbers

Here’s why rounding numbers in JavaScript is still a problem

4 min readMar 4, 2020

--

Press enter or click to view image in full size
Photo by Nick Hillier on Unsplash.

It is 2020 (or maybe2020.0000000000000004) and rounding numbers is still a problem in JavaScript. Actually, it’s a problem in computing in general.

Here is a definitive guide on how to do this properly using JavaScript. Read through once and remember forever!

Introduction

First of all, let’s understand why floating numbers have been, are, and will continue to be a problem in computing.

Each number is a sequence of bytes. For example, the decimal number 3 is binary 00000011. That’s basically how computers represent each number — with bytes (i.e. one byte is 8 bits: 0or1). If we take eight bytes, 00000000 is equivalent to 0 in a decimal system. 11111111 is equivalent to 255. Each byte has a weight. Starting from the left, it goes 128,64, 32, 16, 8, 4, 2, 1. After adding this together, we get 255. Therefore, to convert from binary to decimal, we look at each byte, multiply each byte by its weight and sum up:

00000011 = 0*128 + 0*64 + 0*32 + 0*16 + 0*8 + 0*4 + 1*2 + 1*1 = 3
10101010 = 1*128 + 0*64 + 1*32 + 0*16 + 1*8 + 0*4 + 1*2 + 1*0 = 170
11111111 = 1*128 + 1*64 + 1*32 + 1*16 + 1*8 + 1*4 + 1*2 + 1*1 = 255

--

--

Arek Jaworski
Arek Jaworski

Written by Arek Jaworski

PhD Student at Queen's University Belfast. Former Software Architect — AWS/Node.JS/JavaScript Contractor and Tutor. Combing industry experience with research!

No responses yet