Parsing String to Number

Data Types

Parsing String to Number

🙋 Need help? Ask an expert now!

As mentioned before, strings can be parsed to numbers. We already explored how to use string | 0 to convert a string into an integer. However, the methods parseInt and parseFloat can also to be used to convert strings into either floating-point numbers or an integer. parseInt and parseFloat exhibit a strange behavior you should keep in mind. If a non-number string starts with a number, only the number is extracted from the string when the method is called. An example of this is shown below with str_1 and str_2.

The sample code above has two different scenarios, one with a string only consisting of digits and the other with a string consisting of both digits and letters. The first two parseInt() and parseFloat() methods work normally and convert the whole string into an integer/float. str_1 and str_2 are a little more complicated as the string contains letters as well. In this case, the letters after the numbers are ignored. Therefore, "Hello" is ignored when the method is called and console.log() messages will print "123" and "12.3" respectively. This is the "strange" behavior exhibited by the parseInt() and parseFloat() method that you should be aware of when writing your own code.

Edit Me on GitHub!

Application Question

Consider the following statement:

let varOne = "100100";

Which of the following statements correctly parses the string varOne into an integer?