Converting strings to numbers with vanilla JavaScript | String to number js
November6,2017InJavaScript,youcanrepresentanumberisanactualnumber(ex.42),orasastring(ex.42).Ifyouweretouseastrictcomparisontocomparethetwo,itwouldfailbecausethey’retwodifferenttypesofobjects.varnum1=42;varnum2=42;if(num1===num2){console.log(true);}else{console.log(false);}//Willlog`false`Today,let’slookatthreedifferentwaystoconvertastringintoanumber.parseInt()TheparseInt()methodconvertsastringintoaninteger(awholenumber).Itacceptstwoarguments.Thefirstargumentisthestringtoconvert.Thesecondargu...
November 6, 2017In JavaScript, you can represent a number is an actual number (ex. 42), or as a string (ex. 42).
If you were to use a strict comparison to compare the two, it would fail because they’re two different types of objects.
var num1 = 42; var num2 = 42; if (num1 === num2) { console.log(true); } else { console.log(false); } // Will log `false`Today, let’s look at three different ways to convert a string into a number.
parseInt()The parseInt() method converts a string into an integer (a whole number).
It accepts two arguments. The first argument is the string to convert. The second argument is called the radix. This is the base number used in mathematical systems. For our use, it should always be 10.
var text = 42px; var integer = parseInt(text, 10); // returns 42 parseFloat()The parseFloat() method converts a string into a point number (a number with decimal points). You can even pass in strings with random text in th...