dougajmcdonald dougajmcdonald - 29 days ago 5
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

toLocaleString()
? or to use
NumberFormat
explicitly with values I define?

I see examples using locale codes, and some using other values ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString ) but these don't cover my use case.

Answer

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");
//12a342x2