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 aradix
– Jaromanda X Commented Jan 7, 2023 at 3:38
4 Answers
Reset to default 2All 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条)