How to convert a string to a number in JavaScript?

0
276
views

If you know that your string is a numeric value then a quick form is to simply add a ‘+’ prefix. This works for both integers and floating point numbers.

var s = "123.45";
var n = +s;
 
console.log( s, typeof s ); // 123.45 string
console.log( n, typeof n ); // 123.45 number

Alternatively, you can convert using the Number object.

var s = "123.45";
var n = Number(s);
 
console.log( s, typeof s ); // 123.45 string
console.log( n, typeof n ); // 123.45 number

If your string might contain non numeric characters then you can use parseInt() or parseFloat() functions.

var s = "123";
var n = parseInt(s,10);
 
console.log( s, typeof s ); // 123 string
console.log( n, typeof n ); // 123 number
 
 
var s = "123.45"; // 123.45 string
var n = parseFloat(s); // 123.45 number
 
console.log( s, typeof s );
console.log( n, typeof n );

LEAVE A REPLY

Please enter your comment!
Please enter your name here