CODEX

The Problem With Decimal Subtraction In JavaScript

Why does 544 -306.09 = 237.91000000000003?

Bharathiraja
CodeX
Published in
3 min readMar 20, 2021

--

JS Subtraction Decimal Problem

If you have not worked with financial data, then you never came to know the problem with the decimals( This is just my opinion only). Why because I realized the problem with the decimals only when I worked with finance data. The finance data mostly had decimal values. While doing the arithmetic operation on the decimal value, especially subtraction of two decimal numbers, we will get too many fractional digits.

In this tutorial, we are going to see the problem we face while doing the subtraction with JavaScript using decimals and how to solve it using JavaScript (TypeScript).

Basic Subtraction:

Let take two decimal numbers and subtract them like below.

544 - 306.09 = 237.91000000000003

We got an output of 237.91000000000003. The output had two many decimal digits. The expected output will be only two decimal digits. However, Javascript gave us 14 digits. This kind of subtraction will cause more trouble while dealing with financial data. This will cause a big problem while delivering the software to the customer.

To address this problem, I created a solution.

--

--

Bharathiraja
CodeX
Writer for

AWS | DevOps | Kubernetes | Terraform| Angular | Deep&Machine Learning, Ionic, Full Stack Developer. Learn more at https://github.com/bharathirajatut