3

i want convert my string into number

var string = '1234'
var check = Number(string);

console.log(check);

but if i give my string like below, it wont convert correctly.

var string = '1,234'
var check = Number(string);

console.log(check);

Is there any alternate available?

Kumaresan Sd
  • 1,399
  • 4
  • 16
  • 34
  • 4
    you need to normalize your string to a parsable value. that means you need to strip of all unwanded characters. – Nina Scholz Jan 23 '19 at 12:20

1 Answers1

4

You have to remove all the non numeric characters from string for this to work.

var string = '1,234'

var check = Number(string.replace(',',''));

console.log(check);
ellipsis
  • 12,049
  • 2
  • 17
  • 33
  • Please try to avoid answering duplicated questions, rather flag them as such. – Alexandre Elshobokshy Jan 23 '19 at 12:23
  • Is there any other solution available for this issue? – Kumaresan Sd Jan 24 '19 at 06:59
  • There are other solutions for doing this, but the logic will be the same. All the non-numeric values will be removed first and then the numbers left in string form will be converted to number. You can use splice regex and many other ways to remove the comma(as in above example.) But ultimately every method will do the same thing, in different way – ellipsis Jan 24 '19 at 07:03