What's the "best" way to convert a number to a string (in terms of speed advantage, clarity advantage, memory advantage, etc) ?
Some examples:
String(n)
n.toString()
""+n
n+""
What's the "best" way to convert a number to a string (in terms of speed advantage, clarity advantage, memory advantage, etc) ?
Some examples:
String(n)
n.toString()
""+n
n+""
If you need to to format the result to a specific number of decimal places, for example to represent currency, you need something like the
toFixed()
method.digits
is the number of digits to display after the decimal place.The simplest way to convert any variable to a string is to add an empty string to that variable.
If you are curious as to which is the most performant check this out where I compare all the different Number -> String conversions.
Looks like
2+''
or2+""
are the fastest.https://jsperf.com/int-2-string
Source
Method
toFixed()
will also solves the purpose.Tongue-in-cheek obviously:
Or in ES6 you could simply use template strings: