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

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+""

This question is related to javascript string performance coding-style numbers

The answer is


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.


Just come across this recently, method 3 and 4 are not appropriate because how the strings are copied and then put together. For a small program this problem is insignificant, but for any real web application this action where we have to deal with frequency string manipulations can affects the performance and readability.

Here is the link the read.


The only valid solution for almost all possible existing and future cases (input is number, null, undefined, Symbol, anything else) is String(x). Do not use 3 ways for simple operation, basing on value type assumptions, like "here I convert definitely number to string and here definitely boolean to string".

Explanation:

String(x) handles nulls, undefined, Symbols, [anything] and calls .toString() for objects.

'' + x calls .valueOf() on x (casting to number), throws on Symbols, can provide implementation dependent results.

x.toString() throws on nulls and undefined.

Note: String(x) will still fail on prototype-less objects like Object.create(null).

If you don't like strings like 'Hello, undefined' or want to support prototype-less objects, use the following type conversion function:

/**
 * Safely casts any value to string. Null and undefined are converted to ''.
 * @param  {*} value
 * @return {string}
 */
function string (str) {
  return value == null ? '' : (typeof value === 'object' && !value.toString ? '[object]' : String(value));
}

With number literals, the dot for accessing a property must be distinguished from the decimal dot. This leaves you with the following options if you want to invoke to String() on the number literal 123:

123..toString()
123 .toString() // space before the dot 123.0.toString()
(123).toString()

Tongue-in-cheek obviously:

var harshNum = 108;
"".split.call(harshNum,"").join("");

Or in ES6 you could simply use template strings:

var harshNum = 108;
`${harshNum}`;

I'm going to re-edit this with more data when I have time to, for right now this is fine...

Test in nodejs v8.11.2: 2018/06/06

_x000D_
_x000D_
let i=0;_x000D_
    console.time("test1")_x000D_
    for(;i<10000000;i=i+1){_x000D_
     const string = "" + 1234;_x000D_
    }_x000D_
    console.timeEnd("test1")_x000D_
    _x000D_
    i=0;_x000D_
    console.time("test1.1")_x000D_
    for(;i<10000000;i=i+1){_x000D_
     const string = '' + 1234;_x000D_
    }_x000D_
    console.timeEnd("test1.1")_x000D_
    _x000D_
    i=0;_x000D_
    console.time("test1.2")_x000D_
    for(;i<10000000;i=i+1){_x000D_
     const string = `` + 1234;_x000D_
    }_x000D_
    console.timeEnd("test1.2")_x000D_
    _x000D_
    i=0;_x000D_
    console.time("test1.3")_x000D_
    for(;i<10000000;i=i+1){_x000D_
     const string = 1234 +  '';_x000D_
    }_x000D_
    console.timeEnd("test1.3")_x000D_
    _x000D_
    _x000D_
    i=0;_x000D_
    console.time("test2")_x000D_
    for(;i<10000000;i=i+1){_x000D_
     const string = (1234).toString();_x000D_
    }_x000D_
    console.timeEnd("test2")_x000D_
    _x000D_
    _x000D_
    i=0;_x000D_
    console.time("test3")_x000D_
    for(;i<10000000;i=i+1){_x000D_
     const string = String(1234);_x000D_
    }_x000D_
    console.timeEnd("test3")_x000D_
    _x000D_
    _x000D_
    i=0;_x000D_
    console.time("test4")_x000D_
    for(;i<10000000;i=i+1){_x000D_
     const string = `${1234}`;_x000D_
    }_x000D_
    console.timeEnd("test4")_x000D_
    _x000D_
    i=0;_x000D_
    console.time("test5")_x000D_
    for(;i<10000000;i=i+1){_x000D_
     const string = 1234..toString();_x000D_
    }_x000D_
    console.timeEnd("test5")_x000D_
    _x000D_
    i=0;_x000D_
    console.time("test6")_x000D_
    for(;i<10000000;i=i+1){_x000D_
     const string = 1234 .toString();_x000D_
    }_x000D_
    console.timeEnd("test6")
_x000D_
_x000D_
_x000D_

output

test1: 72.268ms
test1.1: 61.086ms
test1.2: 66.854ms
test1.3: 63.698ms
test2: 207.912ms
test3: 81.987ms
test4: 59.752ms
test5: 213.136ms
test6: 204.869ms

I used https://jsperf.com to create a test case for the following cases:

number + ''
`${number}`
String(number)
number.toString()

https://jsperf.com/number-string-conversion-speed-comparison

As of 24th of July, 2018 the results say that number + '' is the fastest in Chrome, in Firefox that ties with template string literals.

Both String(number), and number.toString() are around 95% slower than the fastest option.

performance tests, description above


If I had to take everything into consideration, I will suggest following

var myint = 1;
var mystring = myint + '';
/*or int to string*/
myint = myint + ''

IMHO, its the fastest way to convert to string. Correct me if I am wrong.


If you need to format the result to a specific number of decimal places, for example to represent currency, you need something like the toFixed() method.

number.toFixed( [digits] )

digits is the number of digits to display after the decimal place.


You can call Number object and then call toString().

Number.call(null, n).toString()

You may use this trick for another javascript native objects.


I like the first two since they're easier to read. I tend to use String(n) but it is just a matter of style than anything else.

That is unless you have a line as

var n = 5;
console.log ("the number is: " + n);

which is very self explanatory


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.


I think it depends on the situation but anyway you can use the .toString() method as it is very clear to understand.


The simplest way to convert any variable to a string is to add an empty string to that variable.

5.41 + ''    // Result: the string '5.41'
Math.PI + '' // Result: the string '3.141592653589793'

...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


The below are the methods to convert a Integer to String in JS

The methods are arranged in the decreasing order of performance.

(The performance test results are given by @DarckBlezzer in his answer)

var num = 1

Method 1:

num = `${num}`

Method 2:

num = num + ''

Method 3:

num = String(num)

Method 4:

num = num.toString()

Note: You can't directly call toString() on a number. 2.toString() will throw Uncaught SyntaxError: Invalid or unexpected token.


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+'' or 2+"" are the fastest.

https://jsperf.com/int-2-string


.toString() is the built-in typecasting function, I'm no expert to that details but whenever we compare built-in type casting verse explicit methodologies, built-in workarounds always preferred.


We can also use the String constructor. According to this benchmark it's the fastest way to convert a Number to String in Firefox 58 even though it's slower than " + num in the popular browser Google Chrome.


Method toFixed() will also solves the purpose.

var n = 8.434332;
n.toFixed(2)  // 8.43

It seems similar results when using node.js. I ran this script:

let bar;
let foo = ["45","foo"];

console.time('string concat testing');
for (let i = 0; i < 10000000; i++) {
    bar = "" + foo;
}
console.timeEnd('string concat testing');


console.time("string obj testing");
for (let i = 0; i < 10000000; i++) {
    bar = String(foo);
}
console.timeEnd("string obj testing");

console.time("string both");
for (let i = 0; i < 10000000; i++) {
    bar = "" + foo + "";
}
console.timeEnd("string both");

and got the following results:

? node testing.js
string concat testing: 2802.542ms
string obj testing: 3374.530ms
string both: 2660.023ms

Similar times each time I ran it.


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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to performance

Why is 2 * (i * i) faster than 2 * i * i in Java? What is the difference between spark.sql.shuffle.partitions and spark.default.parallelism? How to check if a key exists in Json Object and get its value Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly? Most efficient way to map function over numpy array The most efficient way to remove first N elements in a list? Fastest way to get the first n elements of a List into an Array Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3? pandas loc vs. iloc vs. at vs. iat? Android Recyclerview vs ListView with Viewholder

Examples related to coding-style

Method Call Chaining; returning a pointer vs a reference? 80-characters / right margin line in Sublime Text 3 Cannot find reference 'xxx' in __init__.py - Python / Pycharm How to stick <footer> element at the bottom of the page (HTML5 and CSS3)? Simple way to create matrix of random numbers Is calling destructor manually always a sign of bad design? Count all values in a matrix greater than a value Iterate through a C++ Vector using a 'for' loop Which comment style should I use in batch files? Dictionaries and default values

Examples related to numbers

how to display a javascript var in html body How to label scatterplot points by name? Allow 2 decimal places in <input type="number"> Why does the html input with type "number" allow the letter 'e' to be entered in the field? Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array Input type "number" won't resize C++ - how to find the length of an integer How to Generate a random number of fixed length using JavaScript? How do you check in python whether a string contains only numbers? Turn a single number into single digits Python