Convert a Number to a String
By Stephen Bucaro
In many instances, Java Script automatically converts numbers to strings.
For example, anytime you display a number using document.write or alert,
Java Script automatically converts the number to a string for display.
var n = 10 + 2;
alert(n);
var n = 10 + 2;
document.write(n);
Both of the code snippets above will cause the string "12" to display.
A quick way to convert a number to a string is to use the string
concatenation operator (+) as shown below.
var t = 118;
var s = t + " degrees f";
document.write(s);
The code above will display the string "118 degrees f".
You don't actually need any characters in the concatenated string to convert a
number to a string, as shown below.
var n = 3.14152;
alert(typeof n);
n = 3.14152 + "";
alert(typeof n);
The fist message box will display the type of n as "number", after concatenating
an empty string to the variable n, the second message box will display the type
of n as "string".
The code below casts the number 3.14152 to a string by passing it to a String
object constructor.
var n = 3.14152;
var s = String(n);
alert(typeof s);
The proper way to convert a number to a string is to use the Number
object's toString method, as shown below.
var n = 3.14152;
s = n.toString();
alert(typeof s);
why would you want to convert a number to a string? After performing a calculation,
you may need to format the result for display. The code shown below formats the
number 32.6738 to $ 32.67 for display as a currency value.
var k = 32.6738;
m = k.toString();
var n = m.substring(0,m.indexOf(".") + 3);
var amt = "$ " + n;
alert(amt);
In many instances, Java Script automatically converts numbers to strings, but you
can use the String object constructor or the toString method to
explicitly convert a number to a string.
More Java Script Code: • Remove Blank Spaces From Ends of a String • JavaScript Character Escape Sequences • A Brief History of JavaScript • Access Web Page Elements With getElementById • Use Escape to Replace Dangerous Characters • The Document Object Model (DOM) • Window onload Event • Java Script Arithmetic Operators • Interactively Set Webpage Colors • Java Script Trigonometric Methods
|