0

I have written a script that will allow me to add a "," after each 3rd character. After looking at it again, I realised that the client brief stated that it needed to count from the back, not the front.

So $ 3000 should become $ 3,000. At the moment my script makes it $ 300,0 (ignore the $ as it is not part of the string)

Here is my script:

value.match(/.{1,3}/g).join(',')

Does anyone please have any advice about how I might update this to get the desired result? Or perhaps any advice on doing it in a different way?

Any advice would be greatly appreciated

phunder
  • 1,607
  • 3
  • 17
  • 33

1 Answers1

2

Maybe Number.prototype.toLocaleString can come to the rescue?

const amount = `$ 3000`;
const amountNumeric = +amount.replace(/[^\d]/, "");
console.log(amount.replace(/(\d+)/, amountNumeric.toLocaleString("US-us")));

// for fun: as oneliner
const toLocaleAmount = (amount, locale = "US-us") => 
  `${amount.replace(/\d+|\./g, "")}${(+amount.match(/(\d+)/g).join(".")).toLocaleString(locale)}`
console.log(toLocaleAmount("$ 3000"));
console.log(toLocaleAmount("€ 32200.04", "FR-fr"));
console.log(toLocaleAmount("¥ 121009.98"));
console.log(toLocaleAmount("€ 2321.25", "NL-nl"));
.as-console-wrapper { top: 0; max-height: 100% !important; }
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • Thank you kindly for the reply. Someone else has however suggested looking at this post, which has a simpler single-line solution: https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript – phunder Apr 29 '20 at 16:34