0

I'm trying to add +20,2 to this sum with dot 9990.95 or this sum with comma 9990,95 with js or jquery

<span class="sum">9990.95</span>

var price = $( '.sum' ).text(),
    calc  = parseInt( price, 10 ) + 20,
    total = calc.toFixed( 2 );

Return me 9990 without decimal

I tried like this too

var price = $( '.sum' ).text(),
    calc  = 20,
    total = price + calc;

The output was 9990.9920, which is not correct either.

Is there a way how to do that?

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
colapsnux
  • 872
  • 2
  • 15
  • 32
  • 1
    How do you know it returns `9990`? And you are looking for the `parseFloat` function. – Ram Jun 18 '16 at 18:41
  • Possible duplicate of [How to convert string into float in javascript?](http://stackoverflow.com/questions/642650/how-to-convert-string-into-float-in-javascript) Please, search next time. – nicael Jun 18 '16 at 18:49

2 Answers2

2

parseInt does exactly, what the label says -- parsing a string to an integer. Integers do not have decimals by definition.

Instead, use parseFloat:

calc = parseFloat(price) + 20,
nicael
  • 18,550
  • 13
  • 57
  • 90
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
2

I think OP is looking for a way to parse numbers with point or comma as decimal separator into a floating point Number:

let parseDecimalPoint = Number.parseFloat;
    parseDecimalComma = str => Number.parseFloat(str.replace('.', '').replace(',', '.'))

console.log(parseDecimalComma("+20,2") + parseDecimalComma("9990,95"));
console.log(parseDecimalComma("+20,2") + parseDecimalPoint("9990.95"));

See also Javascript parse float is ignoring the decimals after my comma

Community
  • 1
  • 1
le_m
  • 19,302
  • 9
  • 64
  • 74