Home > Software design >  Insert comma into digits and decimal number with regex
Insert comma into digits and decimal number with regex

Time:06-18

I saw many posts to insert comma into just digits or decimal numbers, but not both, so let me ask here.

1234 -> 1,234
1234567 -> 12,34,567
123 -> 123
1234.123 -> 1,234.123
0.123 -> 0.123
0.12345 -> 0.12345

I wanna insert comma like this using regex but I cannot make one which support both digits and decimal numbers.

I tried these but didnt work....

/(\d)(?=(\d{3}) )/
/\B(?=(\d{3}) (?!\d))\.?\d*/

Any idea to make it work?

CodePudding user response:

You may use this regex in Javascript (modern Javascript supports lookbehind):

(?<!\.\d*)(\d)(?=(?:\d{3}) (?:\.|$))

RegEx Details:

  • (?<!\.\d*): Negative lookbehind to assert that we don't have a decimal point before current position
  • (\d): Match a digit and capture in group #1
  • (?=: Start Lookahead
    • (?:\d{3}) : Make sure we have 1 or more sets of 3 digits ahead
    • (?:\.|$): that is followed by a dot or end of line
  • ): End Lookahead

RegEx Demo 1

Or if you're on PCRE then use:

\.\d $(*SKIP)(*F)|(\d)(?=(?:\d{3}) (?:\.|$))

RegEx Demo 2

CodePudding user response:

You can use this regex with substitution

(?=(?<!\.)(?!^)\d{3}(?:\b|(?:\d{3}) )\b)

See the regex demo

JavaScript Example

function format(string) {
  let pattern = /(?=(?!^)\d{3}(?:\b|(?:\d{3}) )\b)/g;
  if (string.includes('.')) {
    pattern = /(?=(?!^)\d{3}(?:\b|(?:\d{3}) )\b\.)/g;
  }
  return string.replace(pattern, ',');
}

console.log('1234', '->', format('1234'));
console.log('123', '->', format('123'));
console.log('1234.123', '->', format('1234.123'));
console.log('0.123', '->', format('0.123'));
console.log('12345642.234234', '->', format('12345642.234234'));

  • Related