简体   繁体   English

如何将 JavaScript 中的数字转换为字符串?

[英]how to convert number to string in JavaScript?

I want to convert a number to string in JS, which is the best and recommaded way to do that?我想在 JS 中将数字转换为字符串,这是最好的推荐方法吗?

I have tried the method shared on W3school so far.到目前为止,我已经尝试过W3school 上共享的方法。 but want to know the recommaded methods from experts但想知道专家推荐的方法

Seems that var str = '' + num is the fastest way to convert a number to a string (num being the number variable).似乎var str = '' + num是将数字转换为字符串的最快方法(num 是数字变量)。

let num = 5
var str = '' + num

(results based on this benchmark: http://jsben.ch/#/ghQYR ) (基于此基准的结果: http://jsben.ch/#/ghQYR

You can use the built in function: toString():您可以使用内置的 function: toString():

Example:例子:
let number = 3
let stringed_number = number.toString()

All of these will work:所有这些都将起作用:

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

I recommend using.我推荐使用。 toLocaleString if you want pretty formatting, like commas or periods for grouping. toLocaleString如果你想要漂亮的格式,比如用于分组的逗号或句点。

However if you know you don't want pretty formatting you should use.toString但是,如果你知道你不想要漂亮的格式,你应该使用.toString

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM