Deeper Look into Parsing Strings into Numbers in JavaScript

Contents

In a Javascript application, the input data we accept from users are often in string format. Forms and input fields are the biggest examples of thisa. But our application can’t always process all these data as strings themselves. Especially when it comes to inputs like age, price, or quantity, the application might need to convert them to “number” type before processing.

Because of this, we have to carry out many string parsing operations while coding. To accomplish this task, Javascript provides different methods, including parseInt and parseFloat, that we can easily use without any hassle. But from these methods, which one fits which type of task? And what’s the behavior you should expect when working with these methods?

In this tutorial, we will look deeper into these parsing methods in Javascript, identify their similarities and differences, and understand when to use each of them. So, without any more delay, let’s get started.

Javascript String to Integer Parsing with ParseInt()

Javascript parseInt parses strings into integers. If the passed string doesn’t contain a number, it returns NaN as the result.

``````parseInt("10") //10
parseInt("No number in string") //NaN
``````

You can parse a string containing non-numerical characters using parseInt as long as it starts with a numerical character. In the search for numerical characters, parseInt ignores any leading whitespaces in the string.

``````parseInt("12 years old") //12
parseInt("    98 pieces") //98
parseInt("new 23 members") //NaN
``````

If the passed string contains more than one number, parseInt always outputs the first number after the type conversion. For example:

``````parseInt("1233 90 322") //1233
``````

When we pass a decimal number to parseInt, it only takes the numerical characters before the decimal point into consideration. This behavior is similar to rounding the decimal into the closest integer.

``````parseInt("23.1")  //23
parseInt("129.67 only")  //129
``````

parseInt also recognizes positive and negative signs in a numerical string and output the integer with the given sign after parsing. In cases like this, there shouldn’t be any other characters, not even whitespaces, between the sign and the number.

``````parseInt("+87 increase")  //87
parseInt("-23 decrease")  //-23
parseInt("   -89") //-89
parseInt("  -  90") //NaN
``````

Another point to note about Javascript’s parseInt is that it can’t identify numbers in scientific exponent-based notation. If you pass a number string in this format, parseInt only extracts the numeric part before the appearance of the “e” character.

``````parseInt("123e100") //123
``````

Interpreting numbers in a specific radix

Usually, parseInt assumes any passed input string is a number in radix 10 (decimal). But parseInt provides a way to change the considered radix using a second argument that accepts a specific radix value from 2 to 36. This way, we can parse binary (2), octal (8), hexadecimal (16), or numbers with any other base in a single step.

Here, we will parse numbers of different radices to see how parseInt works with this radix argument.

``````parseInt("13", 8) //11
parseInt("f2", 16) //242
parseInt("101", 2) //5
parseInt("323", 2) //NaN
``````

Also, if you pass a numeric string starting with “0x” or “0X”, parseInt automatically assumes this number to be hexadecimal (not decimal) even if the radix is not specified.

``````parseInt("0xa1") //161
parseInt("0XF1") //241
``````

Number.parseInt

parseInt method has a counterpart defined in the Javascript Number object with the same name. And this Number.parseInt acts the same way as the global parseInt method.

``````Number.parseInt("10") //10
Number.parseInt("No number in string") //NaN
Number.parseInt("12 years old") //12
Number.parseInt("    98 pieces") //98
Number.parseInt("new 23 members") //NaN
Number.parseInt("23.1")  //23
Number.parseInt("129.67 only")  //129
Number.parseInt("+87 increase")  //87
Number.parseInt("-23 decrease")  //-23
``````

Parsing Decimals with Javascript ParseFloat()

Javascript’s parseFloat behaves much like parseInt except that it can parse floating-point numbers in addition to integers. So, if you want to parse decimal numbers with your code, parseFloat is the method you should go for instead of parseInt.

Most of the rules we discussed under parseInt apply to the parseFloat method too. Here’s a summary of those rules.

• Can parse a number in a string with non-numerical characters as long as it starts with a number.
• Ignore leading or trailing whitespaces.
• Parses only the first number in the string.
• Recognizes + and - signs in the string and outputs the parsed number with the correct sign.

Now, let’s see how parseFloat method works with different types of input under these rules.

``````parseFloat("10.345")  //10.345
parseFloat("No number in string") //NaN
parseFloat("45.23 in height")  //45.23
parseFloat("    900.23 hours")  //900.23
parseFloat("closing 34.234")  //NaN
parseFloat("+1233.1 distance") //1233.1
parseFloat("-122.3454 reduction")  //-122.3454
parseFloat("   -122.1")  //-122.1
parseFloat("233.11 54.1 53.1")  //233.11
``````

parseFloat can also parse integers without converting them into floats during the operation. For example:

``````parseFloat("454")  //454
parseFloat("11 people")  //11
``````

Unlike parseInt, however, parseFloat doesn’t give you an option to specify the radix of the passed number. Instead, it assumes all the input strings are in radix 10. It also doesn’t support the “0x” based hexadecimal notation in the inputs.

``````parseFloat("0xff") //0
``````

One advantage parseFloat has over parseInt is that it can handle instances where scientific notation is used. Here are a few examples of parsing numbers written in this notation.

``````parseFloat("1.345e6")  //1345000
parseFloat("123e100") //1.23e+102
parseFloat("3.15e-4") //0.000315
``````

parseFloat can also recognize and parse “infinity” in a string input.

``````parseFloat("Infinity")  //Infinity
parseFloat("-Infinity")  //-Infinity
``````

Number.parseFloat

Similar to parseInt, parseFloat also has a counterpart Number.parseFloat method that works the same way as the global method. Here are a few examples of its usage.

``````Number.parseFloat("10.345")  //10.345
Number.parseFloat("No number in string") //NaN
Number.parseFloat("45.23 in height")  //45.23
Number.parseFloat("    900.23 hours")  //900.23
Number.parseFloat("closing 34.234")  //NaN
Number.parseFloat("+1233.1 distance") //1233.1
Number.parseFloat("-122.3454 reduction")  //-122.3454
Number.parseFloat("   -122.1")  //-122.1
Number.parseFloat("233.11 54.1 53.1")  //233.11
``````

String to Number Conversion with Number()

In addition to parseInt and parseFloat methods, Javascript provides a third way to parse strings into integers. It’s the Javascript Number() function. However, it can only deal with strings that contain 100% numerical characters, except for leading and trailing whitespaces.

Other than this difference, though, the Number function combines the best qualities of parseInt and parseFloat into a single package:

• Parses both integer and floating-point numbers.

``````Number("456") //456
Number("23.11")  //23.11
Number("  329")  //329
Number("209.12  ")  //209.12
``````
• Returns NaN for inputs that contain non-numerics.

``````Number("Hey")
Number("10k")
``````
• Identifies numbers written in scientific notation.

``````Number("1.345e6")  //1345000
Number("123e100")  //1.23e+102
Number("3.15e-4")  //0.000315
``````
• Recognizes signed numbers.

``````Number("+145")  //145
Number("-56")  //-56
``````
• Supports literal representation of numbers in different bases like “0x” (hexadecimal), “0o” (octal), and “0b” (binary).

``````Number("0x9a")  //154
Number("0b101") //5
Number("0o76")  //62
``````

The Number function behaves in a special way when certain types of inputs are provided. For example, it returns 0 for null and empty string inputs. Also, similar to parseFloat, it accepts “Infinity” as a valid numerical value during string parsing.

``````Number(null)  //0
Number("")  //0
Number("Infinity")  //Infinity
Number("-Infinity")  //-Infinity
``````

Parsing Strings with Unary (+) Operator

Javascript allows us to directly convert purely numerical strings to number type using the unary operator, or the plus sign. Its behavior is more or less the same as the Number function. Below are a few examples of the unary operator in action.

``````+"456"  //456
+"23.11"  //23.11
+"  329" //329
+"209.12  "  //209.12
+"1.345e6"  //1345000
+"123e100"  //1.23e+102
+"3.15e-4"  //0.000315
+"+145"  //145
+"-56"  //-56
+"0x9a"  //154
+"0b101" //5
+"0o76"  //62
+null  //0
+""  //0
+"Infinity"  //Infinity
+"-Infinity"  //-Infinity
``````

Wrapping Up

As we saw in this tutorial, Javascript provides a number of methods that we can use to convert strings into numbers. While all these methods share many similarities, they have unique functionalities that make them fit for different use cases and requirements. With what we covered today, I hope you’ll be able to pick the most suitable parsing method in the future without any confusion and mistakes.