将数字转换为字符串的“最佳”方法是什么(从速度优势、清晰度优势、内存优势等方面考虑)?
一些例子:
字符串(n) n.toString() “”+n n+“”
将数字转换为字符串的“最佳”方法是什么(从速度优势、清晰度优势、内存优势等方面考虑)?
一些例子:
字符串(n) n.toString() “”+n n+“”
当前回答
如果需要将结果格式化为特定的小数位数,例如表示货币,则需要类似toFixed()方法的东西。
number.toFixed( [digits] )
数字是小数点后要显示的位数。
其他回答
我喜欢前两个,因为它们更容易阅读。我倾向于使用String(n),但这只是一个风格问题。
除非你有一行
var n = 5;
console.log ("the number is: " + n);
这不言自明吗
方法toFixed()也可以解决这个问题。
var n = 8.434332;
n.toFixed(2) // 8.43
最近刚遇到这个,方法3和4是不合适的,因为字符串是如何复制然后放在一起的。对于一个小程序来说,这个问题是微不足道的,但是对于任何真实的web应用程序来说,我们必须处理频率字符串操作的这个操作可能会影响性能和可读性。
这是阅读的链接。
...JavaScript的解析器尝试进行解析 作为浮点字面值的数字上的点符号。
2..toString(); // the second point is correctly recognized
2 .toString(); // note the space left to the dot
(2).toString(); // 2 is evaluated first
源
我使用https://jsperf.com为以下用例创建了一个测试用例:
number + ''
`${number}`
String(number)
number.toString()
https://jsperf.com/number-string-conversion-speed-comparison
截至2018年7月24日,结果显示,在Chrome中,数字+”是最快的,在Firefox中,它与模板字符串文字相关联。
String(number)和number. tostring()都比最快的选项慢95%左右。