0

i want to add two float number with fixed two decimal but its converted to string and get concatenated.I know its simple question but actually i'm in hurry

var a=parseFloat("15.24869").toFixed(2)
   var b=parseFloat("15.24869").toFixed(2)

Update when i enter input as

var a=parseFloat("7,191");
var b=parseFloat("359.55");
c=(a+b).toFixed(2)
O/P:NAN

why so?

MayuriS
  • 337
  • 1
  • 4
  • 17

3 Answers3

2

The .toFixed() method returns a string. Call it after you've performed the addition, not before.

var a=parseFloat("15.24869");
var b=parseFloat("15.24869");
var c=(a+b).toFixed(2);

After that, c will be a string too, so you'll want to be careful.

As to your updated additional question, the output is not NaN; it's 366.55. The expression parseFloat("7,191") gives the value 7 because the , won't be recognized as part of the numeric value.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • just to comment. In some cases, that´s not possible as the requirements for example, for tax calculation and the toFixed must be realized in each value before adding (weird tax rules around the world) – Alejandro Teixeira Muñoz May 23 '15 at 12:30
  • 1
    @AlejandroTeixeiraMuñoz true, but doing tax calculations with binary floating point is fundamentally wrong anyway. – Pointy May 23 '15 at 12:32
  • do you mind it´s better to use integers and work with implied decimals? – Alejandro Teixeira Muñoz May 23 '15 at 12:36
  • 1
    @AlejandroTeixeiraMuñoz there are various "big integer" and "big decimal" math packages that provide explicit control over rounding (etc) for financial calculation. It's much slower than JavaScript native numbers but at least you get the right answer :) – Pointy May 23 '15 at 12:40
  • I´m now reading that: http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency and I´m completely agree with that. I´ve been working on a very big billing system (as product parametrization expert) and the system used was that... very clear and usefull.. thanks for the tip. I never minded which one was the main reason. Thanks! – Alejandro Teixeira Muñoz May 23 '15 at 12:42
1

Just add parenthesys to parse float the whole result string

  var a=parseFloat((15.24869).toFixed(2));
  var b=parseFloat((15.24869).toFixed(2));
  c=a+b
0

doing c = a + b adds the two answers together. You might just want to turn them into a string then concatenate them.

var a=parseFloat("15.24869").toFixed(2)
var b=parseFloat("15.24869").toFixed(2)
var c = (a.toString() + b.toString());