How to Add Two Numbers

Fixing the inexact decimal arithmetic by using integer arithmetic

Cristian Salcescu
Frontend Essentials

--

Photo by the author

Adding two numbers should be a simple operation, and in many cases it is.

1 + 2
//3

However, sometimes we get into unexpected issues because the plus operator (+) is both the addition and concatenation operator. When one of the operands is a string it becomes the concatenation operator.

1 + '2'
//'12'

In such cases, we need to make sure both operands are numbers. The Number built-in function can convert any value into a number.

1 + Number('2')
//3

There are cases when we need to add decimal numbers are we are surprised by the result.

0.1 + 0.2
//0.30000000000000004

Luckily for us multiplying and diving by a power of ten gives the precise result. Multiply by a power of ten transforms decimals into integers and the integer arithmetic is exact.

(0.1 * 10 + 0.2 * 10) / 10;
//0.3

To avoid all previous issues we can create a helper function doing the addition.

function add(a, b){
const scale = 4;
const power_of_ten = Math.pow(10, scale);
const aNo = Math.round(Number(a) * power_of_ten);
const…

--

--