3.2.4. Converting Numbers to Strings
Numbers are automatically converted to strings when needed. If a number is used in a string concatenation expression, for example, the number is converted to a string first:
var n = 100; var s = n + " bottles of beer on the wall.";
This conversion-through-concatenation feature of JavaScript results in an idiom that you may occasionally see: to convert a number to a string, simply add the empty string to it:
var n_as_string = n + "";
To make number-to-string conversions more explicit, use the String( ) function:
var string_value = String(number);
Another technique for converting numbers to strings uses thetoString( ) method:
string_value = number.toString( );
The toString( ) method of the Number object (primitive numbers are converted to Number object so that this method can be called) takes an optional argument that specifies a radix, or base, for the conversion. If you do not specify the argument, the conversion is done in base 10. However, you can also convert numbers in other bases (between 2 and 36).[*] For example:
[*] The ECMAScript specification supports the radix argument to thetoString( ) method, but it allows the method to return an implementation-defined string for any radix other than 10. Thus, conforming implementations may simply ignore the argument and always return a base-10 result. In practice, however, implementations do honor the requested radix.
var n = 17; binary_string = n.toString(2); // Evaluates to "10001" octal_string = "0" + n.toString(8); // Evaluates to "021" hex_string = "0x" + n.toString(16); // Evaluates to "0x11"
A shortcoming of JavaScript prior to JavaScript 1.5 is that there is no built-in way to convert a number to a string and specify the number of decimal places to be included, or to specify whether exponential notation should be used. This can make it difficult to display numbers that have traditional formats, such as numbers that represent monetary values.
ECMAScript v3 and JavaScript 1.5 solve this problem by adding three new number-to-string methods to the Number class.toFixed( ) converts a number to a string and displays a specified number of digits after the decimal point. It does not use exponential notation.toExponential( ) converts a number to a string using exponential notation, with one digit before the decimal point and a specified number of digits after the decimal point.toPrecision( ) displays a number using the specified number of significant digits. It uses exponential notation if the number of significant digits is not large enough to display the entire integer portion of the number. Note that all three methods round the trailing digits of the resulting string as appropriate. Consider the following examples:
var n = 123456.789; n.toFixed(0); // "123457" n.toFixed(2); // "123456.79" n.toExponential(1); // "1.2e+5" n.toExponential(3); // "1.235e+5" n.toPrecision(4); // "1.235e+5" n.toPrecision(7); // "123456.8"