1

I'm adding up numbers using Javascript.

I tried using Number and Parsfloat but the number is returned is strange and long...

like 19.0000000

A simple working example is here:

https://jsfiddle.net/7kkqkuhw/

and this is my code:

$(document).on('click','.btn',function(e){

var price = $(this).attr('data-price');


var curPrice = localStorage.getItem('totalPrice');

var setPrice = Number(price) + Number(curPrice);

alert(setPrice);

});

Could someone please let me know what I am doing wrong?

David Hope
  • 1,426
  • 4
  • 21
  • 50
  • try round() if you don't need decimals – JSmith Jun 28 '17 at 20:39
  • @JSmith, I do need the decimals.. a normal calculator would add up 15 + 4.99 and returns 19.99 but my code returns 19.000000000.... etc etc.... – David Hope Jun 28 '17 at 20:41
  • [try this post](https://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-only-if-necessary) – JSmith Jun 28 '17 at 20:43
  • This is a highly relevant page on this https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – Jason Sperske Jun 28 '17 at 20:50
  • There is also [*Is floating point math broken?*](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – RobG Jun 28 '17 at 20:51

2 Answers2

1

Actually, this is a problem related to floating point arithmetic and the way computers do calculations on decimal values.

See this related question on Stack Overflow:
How to deal with floating point number precision in JavaScript?

For instance, when you add 0.1 and 0.2, you won't get 0.3 in JavaScript, and in a lot of other languages that support floating point calculations.

0.1 + 0.2 == 0.30000000000000004

However there are some arithmetic libraries that handle exact arithmetic:

Yet, it is more appropriate to use JSmith's trick:

Math.round(value * 100) / 100
cogk42
  • 13
  • 1
  • 4
1

try this solution JSFiddle link:

$(document).on('click','.btn',function(e){
    var price = $(this).attr('data-price');
    var curPrice = localStorage.getItem('totalPrice');
    var setPrice = Number(price) + Number(curPrice);
    alert(Math.round(setPrice * 100) / 100);
});
JSmith
  • 4,519
  • 4
  • 29
  • 45