Convert a string to an integer? | to integer js
Therearetwomainwaystoconvertastringtoanumberinjavascript.OnewayistoparseitandtheotherwayistochangeitstypetoaNumber.Allofthetricksintheotheranswers(e.g.unaryplus)involveimplicitlycoercingthetypeofthestringtoanumber.YoucanalsodothesamethingexplicitlywiththeNumberfunction.Parsingvarparsed=parseInt("97",10);parseIntandparseFloatarethetwofunctionsusedforparsingstringstonumbers.Parsingwillstopsilentlyifithitsacharacteritdoesntrecognise,whichcanbeusefulforparsingstringslike"92px",butitsalsosomewhat...
There are two main ways to convert a string to a number in javascript. One way is to parse it and the other way is to change its type to a Number. All of the tricks in the other answers (e.g. unary plus) involve implicitly coercing the type of the string to a number. You can also do the same thing explicitly with the Number function.
Parsing
var parsed = parseInt("97", 10);parseInt and parseFloat are the two functions used for parsing strings to numbers. Parsing will stop silently if it hits a character it doesnt recognise, which can be useful for parsing strings like "92px", but its also somewhat dangerous, since it wont give you any kind of error on bad input, instead youll get back NaN unless the string starts with a number. Whitespace at the beginning of the string is ignored. Heres an example of it doing something different to what you want, and giving no indication that anything went wrong:
var widgetsSold = parseInt("97,800", 10); // widgetsSold ...