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
parseFloat can also to be used to convert strings into either floating-point numbers or an integer.
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
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
parseFloat() methods work normally and converts the whole string into an integer/float.
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
parseFloat() method that you should be aware of when writing your own code.