Skip to content

How to add two decimal numbers in JavaScript | Example code

To add two decimal numbers in JavaScript use the toFixed() function to convert it to a string with some decimal places shaved off, and then convert it back to a number.

Output required

0.1 + 0.5  //0.6
0.2 + 0.3  //0.5

But what actually getting

0.1 + 0.2  //0.30000000000000004
0.01 + 0.06  //0.06999999999999999

Solution 1: Use toFixed

+(0.1 + 0.2).toFixed(12) // 0.3

Solution 2: Use Math.round

Math.round((0.1 + 0.2) * 1e12) / 1e12

For example add two decimal numbers in JavaScript

Simple example code script that adds two numbers (decimal numbers) together.

<!doctype html>
  <head>

    <script>
      let a = 0.1;    
      let b = 0.2;

      let res = a + b;
      console.log(res);

      let out = (a + b).toFixed(2);
      console.log(out);


    </script>
  </head>
  <body>

  </body>
  </html>

Output:

How to add two decimal numbers in JavaScript

It looks like IE’s toFixed has some weird behavior, so if you need to support IE something like this might be better:

Math.round((0.1 + 0.2) * 1e12) / 1e12

Source: stackoverflow.com/

Do comment if you have any doubts or suggestions on this JS add number topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

1 thought on “How to add two decimal numbers in JavaScript | Example code”

  1. Also, we can delete unnecessary zeros. When we get stored parseFloat value in variable, we pass this obtained value again through parseFloat.

Leave a Reply

Your email address will not be published. Required fields are marked *