type conversion - how to convert number to string in JavaScript? - Stack Overflow

I want to convert a number to string in JS, which is the best and remaded way to do that?I have tried

I want to convert a number to string in JS, which is the best and remaded way to do that?

I have tried the method shared on W3school so far. but want to know the remaded methods from experts

I want to convert a number to string in JS, which is the best and remaded way to do that?

I have tried the method shared on W3school so far. but want to know the remaded methods from experts

Share Improve this question asked Jan 7, 2023 at 3:20 Shajidur Rahman BappiShajidur Rahman Bappi 211 silver badge3 bronze badges 2
  • 2 use the Number.prototype.toString method - I'm curious, what IS the method shared on W3school? Knowing W3school, it's probably wrong - I would avoid that site like the joke it is, and get better documentation form MDN – Jaromanda X Commented Jan 7, 2023 at 3:23
  • personally, I always use toString since you can specify a radix – Jaromanda X Commented Jan 7, 2023 at 3:38
Add a ment  | 

4 Answers 4

Reset to default 2

All of these will work:

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

Seems that var str = '' + num is the fastest way to convert a number to a string (num being the number variable).

let num = 5
var str = '' + num

(results based on this benchmark: http://jsben.ch/#/ghQYR)

You can use the built in function: toString():

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

I remend using .toLocaleString if you want pretty formatting, like mas or periods for grouping.

However if you know you don't want pretty formatting you should use .toString

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745534751a4631854.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信