How to separate numbers with commas in JavaScript

in Code Write a comment

In this tutorial, you’ll learn how to place a comma every three digits in JavaScript.

var number = 123456
Number(number).toLocaleString() // → 123,456

You can create a function that will take a string, convert it to a number and split this number with commas.

convertToNumber(number) {
  return Number(number).toLocaleString(); 

toLocaleString() method returns a string with a language-sensitive representation of this number. E.g. you can do:

var number = 123456.789;

// German uses comma as decimal separator and period for thousands
// → 123.456,789

// Arabic in most Arabic speaking countries uses Eastern Arabic digits
// → ١٢٣٤٥٦٫٧٨٩

// India uses thousands/lakh/crore separators
// → 1,23,456.789

// the nu extension key requests a numbering system, e.g. Chinese decimal
// → 一二三,四五六.七八九

// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
console.log(number.toLocaleString(['ban', 'id']));
// → 123.456,789

If you like this post, please let me know in the comments section below.
Renat Galyamov

Want to share this with your friends?

PS: Make sure you check other JavaScript tutorials, e.g. shortest “Hello, world!” app in JavaScript frameworks or how to compare operands (values) in JavaScript.

I developed a Vue.js starter kit that you can order today

Order Vue.js starter kit

Write a Comment