Home > Software engineering >  how to convert number to string in JavaScript?
how to convert number to string in JavaScript?

Time:01-07

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

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

CodePudding user response:

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)

CodePudding user response:

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

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

CodePudding user response:

All of these will work:

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

CodePudding user response:

I recommend using .toLocaleString if you want pretty formatting, like commas or periods for grouping.

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

  • Related