Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript convert string to integer

Tags:

javascript

I am just dipping my toe into the confusing world of javascript, more out of necessity than desire and I have come across a problem of adding two integers.

1,700.00 + 500.00

returns 1,700.00500.00

So after some research I see that 1,700.00 is being treated as a string and that I need to convert it.

The most relevant pages I read to resolve this were this question and this page. However when I use

parseInt(string, radix)

it returns 1. Am I using the wrong function or the an incorrect radix (being honest I can't get my head around how I decide which radix to use).

var a="1,700.00";
var b=500.00;
parseInt(a, 10); 
like image 863
tony09uk Avatar asked Aug 09 '26 02:08

tony09uk


1 Answers

Basic Answer

The reason parseInt is not working is because of the comma. You could remove the comma using a regex such as:

var num = '1,700.00';

num = num.replace(/\,/g,'');

This will return a string with a number in it. Now you can parseInt. If you do not choose a radix it will default to 10 which was the correct value to use here.

num = parseInt(num);

Do this for each of your string numbers before adding them and everything should work.

More information

How the replace works:

More information on replace at mdn:

`/` - start  
`\,` - escaped comma  
`/` - end  
`g` - search globally

The global search will look for all matches (it would stop after the first match without this)
'' replace the matched sections with an empty string, essentially deleting them.

Regular Expressions

  • A great tool to test regular expressions: Rubular and more info about them at mdn
  • If you are looking for a good tutorial here is one.

ParseInt and Rounding, parseFloat

parseInt always rounds to the nearest integer. If you need decimal places there are a couple of tricks you can use. Here is my favorite:

2 places: `num = parseInt(num * 100) / 100;`
3 places: `num = parseInt(num * 1000) / 1000;`

For more information on parseInt look at mdn.

parseFloat could also be used if you do not want rounding. I assumed you did as the title was convert to an integer. A good example of this was written by @fr0zenFry below. He pointed out that parseFloat also does not take a radix so it is always in base10. For more info see mdn.

like image 156
EpiphanyMachine Avatar answered Aug 10 '26 16:08

EpiphanyMachine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!