skip to Main Content

I’m trying to write the regex that will format the number like 1231231.00 to 1,231,231.00. I’ve written something like this:

let test = "1231231.00";
console.log(test.replace(/(d)(?=(d{3})+$)/g, "$1,"))

But I still have problem when I try to format 1231231.00. Can anyone give me a hint?

2

Answers


  1. If your goal is to add thousands grouping to a numerical output in a reliable and repeatable manner, try using Intl.NumberFormat():

    let test = "1231231.00";
    let output = Intl.NumberFormat('en', {
      style: 'decimal',
      minimumFractionDigits: 2
    }).format(test);
    
    console.log(output);
    Login or Signup to reply.
  2. The problem is in this:

    (d{3})+$
    

    Your regex is searching for a string of digits, followed by an end-of-string. This assumption breaks if you have a decimal point, because the digits are not immediately followed by the end-of-string.

    Here is a quick fix:

    test.replace(/(d)(?=(d{3})+($|.))/g, "$1,")
    

    I have loosened the check to be "end-of-string or period".


    However, I share the above code primarily for academic/learning purposes.
    In a production system I’d prefer to use a library for this (e.g. Intl.NumberFormat, as mentioned in another answer) rather than hacking something together myself with regex.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search