Last updated: Mar 2, 2024
Reading timeยท2 min
To add strings as numbers:
Number()
constructor to convert it to a number.Number('1') + Number('2')
.const str1 = '5'; const str2 = '15'; const result = Number(str1) + Number(str2); console.log(result); // ๐๏ธ 20 console.log(typeof result); // ๐๏ธ number
We used the Number() constructor to convert two strings to numbers and then we added them using the addition (+) operator.
console.log(5 + '10'); // ๐๏ธ 510
You can use this approach to add multiple strings as numbers.
const str1 = '5'; const str2 = '10'; const str3 = '15'; const result = Number(str1) + Number(str2) + Number(str3); console.log(result); // ๐๏ธ 30
Another very common way to do this is to use the unary plus (+) operator.
The operator is used to convert a string to a number.
const str1 = '5'; const str2 = '15'; const result = +str1 + +str2; console.log(result); // ๐๏ธ 20
The unary plus (+) operator tries to convert a value to a number.
This becomes hard to read because we have 2 unary plus (+) operators and an addition (+) operator.
Both of these examples convert the string to a number. One uses the unary plus
(+) approach and the other uses the Number()
constructor.
const n1 = +'100'; console.log(n1); // ๐๏ธ 100 console.log(typeof n1); // ๐๏ธ number const n2 = Number(100); console.log(n2); // ๐๏ธ 100 console.log(typeof n2); // ๐๏ธ number
Alternatively, you can use the parseInt()
or parseFloat()
functions.
parseInt()
and parseFloat()
to add strings as NumbersIf your strings end with characters, you have to use the parseInt()
function
instead.
const str1 = '5a'; const str2 = '15b'; const result = parseInt(str1, 10) + parseInt(str2, 10); console.log(result); // ๐๏ธ 20
Instead, we used the parseInt() method.
The method takes the following 2 parameters:
An easy way to think about the parseInt
function is that we take as many
digits as we can from the beginning of the string, ignore the rest and convert
the value to a number.
const s1 = parseInt('5abc', 10); console.log(s1); // ๐๏ธ 5 console.log(typeof s1); // ๐๏ธ number
This wouldn't work if the non-numeric characters were at the beginning of the string.
const s1 = parseInt('abc5', 10); console.log(s1); // ๐๏ธ NaN
If you want to convert the strings to floating-point numbers, use the parseFloat() function instead.
const str1 = '12.3abc'; const str2 = '23.4abc'; const result = parseFloat(str1) + parseFloat(str2); console.log(result); // ๐๏ธ 35.7
The parseFloat()
function takes a string as a parameter, parses the string and
returns a floating-point number.
const str1 = '12.3abc'; console.log(parseFloat(str1)); // ๐๏ธ 12.3 const str2 = '23.4abc'; console.log(parseFloat(str2)); // ๐๏ธ 23.4
As with parseInt()
, the parseFloat()
method ignores the non-numeric
characters at the end of the string.