将数字转换为字符串的“最佳”方法是什么(从速度优势、清晰度优势、内存优势等方面考虑)?
一些例子:
字符串(n) n.toString() “”+n n+“”
将数字转换为字符串的“最佳”方法是什么(从速度优势、清晰度优势、内存优势等方面考虑)?
一些例子:
字符串(n) n.toString() “”+n n+“”
当前回答
你可以调用Number对象,然后调用toString()。
号码。调用(null, n) .toString ()
你可以将这个技巧用于其他javascript原生对象。
其他回答
...JavaScript的解析器尝试进行解析 作为浮点字面值的数字上的点符号。
2..toString(); // the second point is correctly recognized
2 .toString(); // note the space left to the dot
(2).toString(); // 2 is evaluated first
源
将任何变量转换为字符串的最简单方法是向该变量添加一个空字符串。
5.41 + '' // Result: the string '5.41'
Math.PI + '' // Result: the string '3.141592653589793'
我们还可以使用String构造函数。根据这个基准测试,它是在Firefox 58中将数字转换为字符串的最快方法,尽管它比Firefox 58慢 + num在流行浏览器谷歌Chrome。
如果我必须把所有的事情都考虑进去的话,我还是建议跟随
var myint = 1;
var mystring = myint + '';
/*or int to string*/
myint = myint + ''
恕我直言,这是转换为字符串的最快方式。如果我错了,请指正。
如果需要将结果格式化为特定的小数位数,例如表示货币,则需要类似toFixed()方法的东西。
number.toFixed( [digits] )
数字是小数点后要显示的位数。