Converting strings to numbers with vanilla JavaScript

Converting strings to numbers with vanilla JavaScript


JavaScript gives us the ability to easily transform a String to a primitive number. But the issue is that if you were to use a strict comparison to compare the two, it would fail because they’re two different types of objects. so let’s see an instance:

 let number1 = 20;
 let number2 = "20";
 console.log(number1 == number2); //true
 console.log(number1 === number2); //false
Let see some ways we could convert strings to number using Javascript.

parseInt()

The parseInt() method converts a string into an integer. This method accepts two arguments, the first argument which is the string to be parsed, while the second argument is the base number used in mathematical systems and its called radix.

let string = "42wisdom";
let integer = parseInt(string, 10);
console.log(integer); // 42

parseFloat()

The parseFloat method converts a string into a number with floating points(a number with decimal points).

let string = "33.4so333meRandomStuff";
let pointNum = parseFloat(string);
console.log(pointNum);

Multiplying by 1


 let string1 = "234";
 let string2 = "0.000003320";
 let string3 = "23px";
 let etring4 = "wisdom";

 console.log(string1 * 1); // 234
 console.log(string2 * 1); // 0.00000332
 console.log(string3 * 1); // NaN
 console.log(string4 * 1); // NaN

Number()

The number() converts strings to numbers, But if you pass in a string with random text in it, it will return NaN which is an acronym for “Not a Number.”

Number("3455") //returns 3455
Number("0.9493") // returns 0.9493
Number("10.949e3") // returns 10949
Number('3.14someRandomStuff'); // returns NaN

Unary Operator


let string = '100';
+string // 100

let string2 = "wisdom"
+string2 // NaN

Math.ceil

This method returns the nearest integer rounded up. And it also accepts Strings as a parameter, making it a way to convert a string to a number.

let string1 = "101";
let string2 = "100.21";
let string3 = "bye";
Math.ceil(string1); // 101
Math.ceil(string2); // 101
Math.ceil(string3); // NaN
Math.ceil(""); // 0

Conclusion

There are many ways of converting strings to integer in JavaScript. It is up to the developer to decide which one they prefer and which is most suitable in some cases.

Share on social media

//