Javascript Convert string to number
- You've got a string, and it contains a number. Maybe it's coming from API or some data that you've imported.
const number = '1234'; console.log(number + 1); // 12341
-
If you add a number, it just appends items onto the end of the string rather than adding them to the actual Number.
-
So, we want to convert this string that contains a number into an actual number.
Using parseInt
Syntax
parseInt(string, radix);
- string - The value to be parsed. If the parameter is not a string, it is converted to a string.
- radix (optional) From 2 to 36, radix string. For example, specifying 16 means that the parsed value is a hexadecimal number.
const number = '1234'; console.log(parseInt(number) + 1); // 1235
Using Number Function
Syntax
Number(object)
- The
Number()
function converts the object argument to a number that represents the object's value.
const number = '1234'; console.log(Number()); // 0 console.log(Number(number)); // 1234
- If you do Not Pass anything, it returns 0.
Using Unary Operator (+)
- Unary operators can be beneficial for converting strings to numbers, and they offer the fastest, most straightforward way to convert.
const number = '1234'; const un = +number; console.log(number, typeof number); // 1234 string console.log(un, typeof un); // 1234 number
Using Multiply with Number
- Multiplying the string with
1
does not change the value and will also be converted to a number.
const number = '5678'; const mul = number * 1; console.log(number, typeof number); // 5678 string console.log(mul, typeof mul); // 5678 number
Using double NOT bitWise operator ( double tilde operator ~~ )
- It is used as a faster substitute for
Math.floor()
for positive numbers. - The double tilde operator is not as much an operator as it's a double NOT bitwise operator / double bitwise negation.
const number = '1234567'; const negNumber = '-1234567'; const dou = ~~number; const dou1 = ~~negNumber; console.log(number, typeof number); // 1234567 string console.log(dou, typeof dou); // 1234567 number console.log(dou1, typeof dou1); // -1234567 number
Using Math.floor()
- This method returns the largest integer (floor value) that is less than or equal to the parameter value
const number = '1234567'; const flo = Math.floor(number); console.log(flo, typeof flo); // 1234567 number
- It is a Little tricky with decimal numbers since it will return the value of the nearest integer as Number.
const number = '13.33'; const flo = Math.floor(number); console.log(flo, typeof flo); // 13 number
const number = '13.63'; const flo = Math.floor(number); console.log(flo, typeof flo); //13