Converting Numbers to Strings

JavaScript FAQ | Numbers FAQ | Strings and RegExp FAQ  

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 ''), for example:

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 toString or concatenating with an empty string.

NOTE: For converting numbers to binary, octal, or hexadecimal strings (or to any other base) see Converting to Another Base.

See also:

  • Converting strings to numbers
  • Can I display mathematical symbols as part of JavaScript output?
  • Mathematical functions in JavaScript
  • Rounding in JavaScript
  • Accuracy of JavaScript arithmetic
  • Copyright © 1999-2012,