String Number conversion in JavaScript

Number to String conversion

To convert a number to string you can append an empty string or you can use toString() method. toString() method is not supported by older browsers.

var num = 30;
num = 30 * 5; // 150
str = num + ""; // or
str = num.toString();

String to number conversion

To convert a String to number, you can perform arithmetic operations like (*, / or -) such that it doesn’t alter the given string value. You might have noticed that I have not included ‘+’ in the above list this is because that JavaScript uses ‘+’ sign for string concatenation so adding ‘123′ + 0 will result into ‘1230′ and not 123. We can also user Number() function to perform the conversion. This is bit slower than any of the above options because this make explicit call to a function to perform conversion. But if you are using this option then it makes very clear that what your code is intended to do. So in my opinion if you are not worried about the performance then you can use Number() function as it will make code very clear.

var str = '123'
num = str * 1;
num = str - 0;
num = str/ 0;
num = Number(str);

If you try any of the above method on a text field which doesn’t contain valid numeric fields then you will get an ‘NaN’ as the result. So be careful :)

Related Post

Rounding number in javascript up to some decimal point
String in Java?
Implicit conversion from data type varchar to money is not allowed
What will be output of the following program?
Create a random number between 1 to 10 excluding 3, 5, and 9.?

Comments

Leave a Reply