Try using replace()
to replace a ,
with nothing
and then parseFloat()
to get the number as float. From the variables in OP, it appears that there may be fractional numbers too, so, parseInt()
may not work well in such cases(digits after decimal will be stripped off).
Use regex inside replace()
to get rid of each appearance of ,
.
var a = parseFloat('1,700.00'.replace(/,/g, ''));
var b = parseFloat('500.00'.replace(/,/g, ''));
var sum = a+b;
This should give you correct result even if your number is fractional like 1,700.55
.
If I go by the title of your question, you need an integer. For this you can use parseInt(string, radix)
. It works without a radix
but it is always a good idea to specify this because you never know how browsers may behave(for example, see comment @Royi Namir). This function will round off the string to nearest integer value.
var a = parseInt('1,700.00'.replace(/,/g, ''), 10); //radix 10 will return base10 value
var b = parseInt('500.00'.replace(/,/g, ''), 10);
var sum = a+b;
Note that a radix is not required in parseFloat()
, it will always return a decimal/base10 value. Also, it will it will strip off any extra zeroes at the end after decimal point(ex: 17500.50
becomes 17500.5
and 17500.00
becomes 17500
). If you need to get 2 decimal places always, append another function toFixed(decimal places)
.
var a = parseFloat('1,700.00'.replace(/,/g, ''));
var b = parseFloat('500.00'.replace(/,/g, ''));
var sum = (a+b).toFixed(2); //change argument in toFixed() as you need
// 2200.00
Another alternative to this was given by @EpiphanyMachine which will need you to multiply and then later divide every value by 100
. This may become a problem if you want to change decimal places in future, you will have to change multiplication/division factor for every variable. With toFixed()
, you just change the argument. But remember that toFixed()
changes the number back to string unlike @EpiphanyMachine solution. So you will be your own judge.