0

I am trying to add few decimal numbers from form input field which is like:

var total = Number(11000.2)+Number(10000.1)+Number(10762.4);
consol.log(total);

consol shows 31762.700000000004

I don't understand from where its getting addition values (00000000004) and showing .700000000004.

Can anyone please explain what is happening here and what I am missing?

Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94
sarojanand
  • 607
  • 1
  • 11
  • 30

1 Answers1

1

This is an age old issue to do with floating point arithmetic. You can read more about it in lots of posts like this: How to deal with floating point number precision in JavaScript?

The typical simple solution to it is to treat decimals as integers then to divide them back to decimals later. Like so:

var a = 0.2;
var b = 0.1;

var r = a + b; // r == 0.300000000004

var r = (10*a + 10*b)/10; // r == 0.3

In your case I'd do it like this:

var factor = 10; 
var total = (factor*11000.2 + factor*10000.1 + factor*10762.4) / factor;

// total == 31762.7
Community
  • 1
  • 1
Charles Clayton
  • 17,005
  • 11
  • 87
  • 120