skip to Main Content

I’m looking for a regex pattern that given 1234, returns 1,234 and given 1234.1234, returns 1,234.1234.

I’m using JavaScript and am using this pattern for an input on the website with real-time data entry.

2

Answers


    1. Split based on the dot if exists.
    2. Introduce commas.
    3. Join back.
    function formatNumber(num) {
        var parts = num.toString().split(".");
        parts[0] = parts[0].replace(/B(?=(d{3})+(?!d))/g, ",");
        return parts.join(".");
    }
    
    Login or Signup to reply.
  1. You can use a regexp

    const formatNumber = num => num.toString().replace(/(?<!..*)B(?=(d{3})+(?!d))/g, ",");
    
    [1234.1234, 1234, 123.4, 322124234.2].forEach(num => console.log(formatNumber(num)));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search