Question: How do I convert numbers to strings in JavaScript?
Answer: The simplest way to convert any variable to a string is to add an empty string to that variable
(i.e. concatenate it with an empty string
a = a+'' // This converts a to string b += '' // This converts b to string 5.41 + '' // Result: the string '5.41' Math.PI + '' // Result: the string '3.141592653589793'Another way to perform this conversion is the toString() method:
a = a.toString() // This converts a to string b = b.toString() // This converts b to string (5.41).toString() // Result: the string '5.41' (Math.PI).toString() // Result: the string '3.141592653589793'
In the above examples, the resultant string will hold
the decimal representation of the original number.
If you would like to guarantee a specific number of decimal places in the conversion result,
you can use the toFixed method rather than using NOTE: For converting numbers to binary, octal, or hexadecimal strings (or to any other base) see Converting to Another Base. See also: |
Copyright © 1999-2012, JavaScripter.net.