Converting Between String and Number Data Types

JavaScript is a loosely typed language and so there are quicker ways to convert variables from one type to another simply by making use of the type conversions that JavaScript applies when dealing with data that would otherwise be of the wrong type to allow the statement to work.

String to Number

You can cast a string to a number using:

num = Number(str);

A shorter way to convert a string into a number is using the unary + operator:

num = +str;

If the string needs to be converted to a number and there is other code in the statement where further calculations are to be applied you can specify it as (+str) so as to ensure that the + isn't misinterpreted.

Number to String

You can cast a number to a string using:

str = String(num);

A shorter way to convert a number to a string is to use the concatenate operator:

str = ""+num;

Because one of the values is a string (admittedly an empty one) it forces the other value to convert to a string in order to concatenate the two strings together.

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate