Skip to content Skip to sidebar Skip to footer

Regular Expression To Prevent Comma Separator If Operand Has Decimal

I found this regex function which add thousand comma separator for an arithmetic expression. But if the operand has decimal, I do not want to add any comma separator. How should

Solution 1:

One option could be using replace with a callback function and match 1+ times a zero followed by a dot and zero.

If that is matched, return it in the replacement, else return a comma.

\b0+\.\d+(?:\.\d+)*|\B(?=(\d{3})+(?!\d))

Regex demo

functionnumberWithCommas(x) {
  const regex = /\b0+\.\d+(?:\.\d+)*|\B(?=(\d{3})+(?!\d))/g;
  return x.toString().replace(regex, (m) => m !== "" ? m : ",");
}

console.log(numberWithCommas("1000"));
console.log(numberWithCommas("1000.03"));
console.log(numberWithCommas("1000.03+2300"));
console.log(numberWithCommas("1000.03+0.2300"));

Solution 2:

Use toLocaleString for this pattern.

The toLocaleString() method returns a string with a language-sensitive representation of this number.

functionnumberWithCommas(x) {
    if (x.includes('+')) {
        return x.split('+').reduce((result, val) => {
            return result + (result == '' ? '' : '+') + Number(val).toLocaleString();
        }, '');
    } else {
        returnNumber(x).toLocaleString()
    }
}

var regex = /[+\-\*\/]/g; 
functionnumberWithCommas(x) {
  if (regex.test(x)) {
    let sign = x.match(regex)[0];
    return x.split(sign).reduce((result, val) => {
      return result + (result == '' ? '' : sign) + Number(val).toLocaleString();
    }, '');
  } else {
    returnNumber(x).toLocaleString()
  }
}

console.log(numberWithCommas("1000"));
console.log(numberWithCommas("1000.03"));
console.log(numberWithCommas("1000.03+2300"));
console.log(numberWithCommas("1000.03-0.2300"));

Post a Comment for "Regular Expression To Prevent Comma Separator If Operand Has Decimal"