0

I am trying to add some integer value to the float (maybe it's not float with this situation this is money format) I have a money value like this: "4,918.05" and i want to add 30 to it.

        var inputs = $('.ig-control__cbx');
        var totalPrice = parseFloat($('.total-price-span').html());
        var add = 30;
        totalPrice = totalPrice +add
        $('.total-price-span').html(totalPrice.toFixed(2));

When i want to sum them i get 4 instead of total. How can i fix it?

yigitozmen
  • 947
  • 4
  • 23
  • 42
  • 1
    `parseFloat` does not recognize comma as a part of `number` so you recive just number before the first unrecognized character – MysterX Mar 09 '17 at 15:37
  • 1
    This is a very basic fact with javascript. this might help http://stackoverflow.com/questions/14496531/adding-two-numbers-concatenates-them-instead-of-calculating-the-sum – Ankit Mar 09 '17 at 15:39
  • @Ankit And which of the answers fits on this question? – Andreas Mar 09 '17 at 15:41

2 Answers2

2

I think I can extend my comment to answer:

So parseFloat does not recognize comma as a part of number so you recive just number before the first unrecognized character. To solve this problem, you need to replace all commas in that string before parsing float. Something like this:

var inputs = $('.ig-control__cbx');

var strVal = $('.total-price-span').html().replace(/,/g,'');
var totalPrice = parseFloat(strVal);

var add = 30;
totalPrice = totalPrice +add
$('.total-price-span').html(totalPrice.toFixed(2));
MysterX
  • 2,318
  • 1
  • 12
  • 11
2

You are getting 4 from parseFloat("4,918.05"). To circumvent this you could use replace() to remove commas first.

var price = $('.total-price-span').html().replace(/,/g,'');
var totalPrice = parseFloat(price);
Nik Weiss
  • 422
  • 7
  • 18