JavaScript toString Method Converts a Number to a String
By Stephen Bucaro
The JavaScript toString method is used to convert a number to a string. It accepts a single
optional parameter which specifies the base in which the number is to be represented in the string.
This is a very convenient method of converting a number to a different base. If called without a
parameter then the digits in the number will be converted to a string directly. Shown below is code
converting a number to a string without specifying a base.
var numValue = 123;
alert("The number is " + numValue.toString());
The output from the above code is "The number is 123". Shown below is code passing the parameter
16 to convert the number from decimal to hexadecimal.
var numValue = 123;
alert("The number is " + numValue.toString(16));
The output from the above code is "The number is 7b". Shown below is code passing the parameter
2 to convert the number from decimal to binary.
var numValue = 213;
alert("The number is " + numValue.toString(2));
The output from the above code is "The number is 11010101". If you are simply converting digits to
a string without changing the base, you can use JavaScript coercion, sometimes called
"type casting". using the + symbol as shown below, JavaScript will automatically convert
the number's digits to a string.
var numValue = 213;
alert("The number is " + numValue);
Or even simply:
alert("The number is " + 213);
Coercion is when JavaScript uses its own discretion to cast a variable to another type. When you
are not explicitly using coercion, as above, it can cause difficult to find errors.
More Java Script Code: • The Screen Object • Convert a Number to a String • Using the Java Script eval() Function • Determine Minimum and Maximum • Java Script Data Types • Java Script Include a Backslash Character in a String • Comparison Operators • Java Script Events • The continue Statement • JavaScript Operators
|