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:


Hi, I'm Renat 👋

 


var number = 123456.789;

// German uses comma as decimal separator and period for thousands
console.log(number.toLocaleString('de-DE'));
// → 123.456,789

// Arabic in most Arabic speaking countries uses Eastern Arabic digits
console.log(number.toLocaleString('ar-EG'));
// → ١٢٣٤٥٦٫٧٨٩

// India uses thousands/lakh/crore separators
console.log(number.toLocaleString('en-IN'));
// → 1,23,456.789

// the nu extension key requests a numbering system, e.g. Chinese decimal
console.log(number.toLocaleString('zh-Hans-CN-u-nu-hanidec'));
// → 一二三,四五六.七八九

// 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.
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/javascript-split-numbers

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.

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment