What's the best way to convert a number to a s

2019-01-01 12:22发布

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

20条回答
千与千寻千般痛.
2楼-- · 2019-01-01 12:24

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.

number.toFixed( [digits] )

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

查看更多
泪湿衣
3楼-- · 2019-01-01 12:27

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'
查看更多
低头抚发
4楼-- · 2019-01-01 12:27

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

查看更多
心情的温度
5楼-- · 2019-01-01 12:28
2..toString(); // the second point is correctly recognized
2 .toString(); // note the space left to the dot
(2).toString(); // 2 is evaluated first

Source

查看更多
零度萤火
6楼-- · 2019-01-01 12:29

Method toFixed() will also solves the purpose.

var n = 8.434332;
n.toFixed(2)  // 8.43
查看更多
孤独寂梦人
7楼-- · 2019-01-01 12:31

Tongue-in-cheek obviously:

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

Or in ES6 you could simply use template strings:

var harshNum = 108;
`${harshNum}`;
查看更多
登录 后发表回答