3 ways to convert numeric string to integer in JavaScript
If you work with JavaScript for sure you got a case when you used addition (+) with number and a numeric string (e.g. “12”).
Since JavaScript is dynamically-typed language result of such an operation can be (at least first time) surprising…
What does it mean JavaScript is dynamically-typed?
Dynamically-typed languages are those (like JavaScript) where the interpreter assigns variables a type at runtime based on the variable’s value at the time.
https://developer.mozilla.org/en-US/docs/Glossary/Dynamic_typing
This is especially case when working with addition operator.
"10" + 1 // ❌"101"
1 + "10" // ❌"110"// but...
"10" - 3 // ✅9
"12" * 3 // ✅36
So what is happening here?
The addition operator produces the sum of numeric operands or string concatenation.
That mean when at least one element is string-type we concentrate it with anything as it would be strings.
"1" + 2 + 3 // "123"
1 + "2" + 3 // "123"
1 + 2 + "3" // 33 ⚠️ because 1 + 2 = 3 and 3 + "3" gives us "33"
1 + 2 + "3" + 4 // 334 ⚠️ again: 1 + 2 = 3; 3 + "3" = "33"; "33" + 4 = "334"
So how to sum numeric string(s) with numbers properly?
First we need to convert sting to number. There are several ways to do it. Let’s dive in…
Convert string to number
Method #1: parseInt (parseFloat)
First method, oldest one, is to parse integer. For this we use parseInt
(or parseFloat
if we need float number).
parseInt
accepts two parameters:
- string — that’s string we want to parse
NOTE if it’s not a sting-type then it’s first converted to string - radix — see below for MDN parameter documentation
An integer between
2
and36
that represents the radix (the base in mathematical numeral systems) of thestring
. Be careful—this does not default to10
!https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
Some examples of parseInt
parseInt("15", 10) // 15
parseInt("15.345", 10) // 15 (we asked for integer and not float)
parseInt(15.345, 10) // 15
If input for some reason can’t be converted to integer we will get NaN (Not-A-Number) in response:
parseInt("Hello World", 10) // NaN
Examples of parseFloat
NOTE parseFloat
accepts only one parameter - the value you want to parse. Moreover this must be a string or a number.
parseFloat("15.345") // 15.345
Nice but we need to write a bit code to get integer (or float) from string with those methods. Let’s check if there are easier ways achieving this…
Method #2: Number()
Converting string to either integer or floating point is way easier with Number
The
Number
JavaScript object is a wrapper object allowing you to work with numerical values. ANumber
object is created using theNumber()
constructor. A primitive type object number is created using theNumber()
function.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number
When using Number
in a non-constructor context (without the new operator) it can be used to perform a type conversion.
That’s what we do in following examples:
// convert integer
Number("123") // 123// convert floating point number
Number("3.1415") // 3.1415 // if input can't be converted to numeric - Number returns NaN
Number("Hello World") // NaN
Nice and clean. Right? But there is even shorter way to the same!
Method #3. Unary plus (+)
The unary plus operator precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn’t already. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number. It can convert string representations of integers and floats, as well as the non-string values
true
,false
, andnull
. Integers in both decimal and hexadecimal ("0x"-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate toNaN
.
That long description means basically we can (try to) convert many types (incl. string, boolean) to integer (or float).
See some examples:
// converting integer
+"33" // 33
+"01234" // 1234// float is convertible, too
+3.1415 // 3.1415
+"3.1415" // 3.1415// converting true, false and null values
+false // 0
+true // 1
+null // 0// converting non-numeric results in NaN (Not-A-Number)
+"Hello world" // NaN
The simplest and shortest way to convert to integer / float is to use unary operator.
Testing all methods
Let’s check out what we can do with example we started from:
"10" + 1 // ❌"101"
1 + "10" // ❌"110"
Using parseInt
/ parseFloat
parseInt("10", 10) + 1 // ✅11
1 + parseInt("10", 10) // ✅11parseFloat(10) + 1 // ✅11
Using Number()
Number("10") + 1 // ✅11
1 + Number("10") // ✅11
Using unary plus
+"10" + 1 // ✅11
1 + +"10" // ✅11
As you can see every method converts string representation of number to either integer or float allowing us properly sum numbers.
Bonus: isNaN()
To prevent NaN result while converting string to integer/float we can first check if string value can be converted to number.
The
isNaN()
function determines whether a value isNaN
or not.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
Some examples:
isNaN("10") // false
isNaN("10.12") // false
isNaN("10.ab") // true
Did you know all 3 methods? Which one do you prefer? Let me know — I’m curious :)
Personally I use unary operator most of the time. However when I make a code that I know will be reused by other devs I prefer Number()
— it’s more clear about what it does.