Dasha Salo
Dasha Salo

Reputation: 5169

RegExp: currency format

I need to format numbers so that thousands were not separated by anything and hundreds were separated with a dot. For example

1234.56 12.34 123

I wrote the following ReqExp

amountValue.replace(/^(\d+)[,.](\d{3})[.,](\d{2})$/,'$1' + '$2' +'.'+'$3').replace(/^(\d+),(\d{2})$/,'$1' +'.'+'$2');

If there a way to make it shorter?

Thank you!

Upvotes: 1

Views: 1432

Answers (2)

Gumbo
Gumbo

Reputation: 655379

I would just remove any non numeric character that’s not the decimal point:

amountValue.replace(/[^0-9](?!\d{2}$)/, '').replace(/,(?=\d{2}$)/, '.');

Upvotes: 1

cjk
cjk

Reputation: 46445

I think this might work:

amountValue.replace(/^(\d*)[,.]?(\d{0,3})[.,](\d{2})$/,'$1' + '$2' +'.'+'$3');

Try it against your data.

Upvotes: 1

Related Questions