What's the best way to convert a number to a string in JavaScript?

608,576

Solution 1

like this:

var foo = 45;
var bar = '' + foo;

Actually, even though I typically do it like this for simple convenience, over 1,000s of iterations it appears for raw speed there is an advantage for .toString()

See Performance tests here (not by me, but found when I went to write my own): http://jsben.ch/#/ghQYR

Fastest based on the JSPerf test above: str = num.toString();

It should be noted that the difference in speed is not overly significant when you consider that it can do the conversion any way 1 Million times in 0.1 seconds.

Update: The speed seems to differ greatly by browser. In Chrome num + '' seems to be fastest based on this test http://jsben.ch/#/ghQYR

Update 2: Again based on my test above it should be noted that Firefox 20.0.1 executes the .toString() about 100 times slower than the '' + num sample.

Solution 2

In my opinion n.toString() takes the prize for its clarity, and I don't think it carries any extra overhead.

Solution 3

Explicit conversions are very clear to someone that's new to the language. Using type coercion, as others have suggested, leads to ambiguity if a developer is not aware of the coercion rules. Ultimately developer time is more costly than CPU time, so I'd optimize for the former at the cost of the latter. That being said, in this case the difference is likely negligible, but if not I'm sure there are some decent JavaScript compressors that will optimize this sort of thing.

So, for the above reasons I'd go with: n.toString() or String(n). String(n) is probably a better choice because it won't fail if n is null or undefined.

Solution 4

...JavaScript's parser tries to parse the dot notation on a number as a floating point literal.

2..toString(); // the second point is correctly recognized
2 .toString(); // note the space left to the dot
(2).toString(); // 2 is evaluated first

Source

Solution 5

Other answers already covered other options, but I prefer this one:

s = `${n}`

Short, succinct, already used in many other places (if you're using a modern framework / ES version) so it's a safe bet any programmer will understand it.

Not that it (usually) matters much, but it also seems to be among the fastest compared to other methods.

Share:
608,576
Pacerier
Author by

Pacerier

# 9

Updated on July 08, 2022

Comments

  • Pacerier
    Pacerier almost 2 years

    What's the "best" way to convert a number to a string (in terms of speed advantage, clarity advantage, memory advantage, etc) ?

    Some examples:

    1. String(n)

    2. n.toString()

    3. ""+n

    4. n+""