dougajmcdonald dougajmcdonald - 1 year ago 117
Javascript Question

Number.toLocaleString() with custom separators

I need to format a number in JavaScript with separators that may be defined at runtime.

The combination of thousand and decimal separator may not match a specific locale.

Is there a way to provide the thousand and decimal separator in JavaScript

? or to use
explicitly with values I define?

I see examples using locale codes, and some using other values ( ) but these don't cover my use case.

Answer Source

One option is to format to a string with known separators, and then do a find/replace with the unknown separators.

function formatNum(num, separator, fraction) {
  var str = num.toLocaleString('en-US');
  str = str.replace(/\./, fraction);
  str = str.replace(/,/g, separator);
  return str;

formatNum(12342.2, "a", "x");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download