Josh
Josh

Reputation: 139

ignore digits after '.' regex

I currently have this function for formatting numbers (adding commas every 3 digits):

formatNumber: (num) => {
        return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
},

The problem is that if the number has more than 3 decimal places, it also adds commas into the decimals. i would like to ignore everything after the ., but still return the number including the decimals. (ignore anything after the decimal, but still return that.)

For example, if I have 1000000.12341234 I would like it to return 1,000,000.12341234

(the current function would return 1,000,000.12,341,234)

Upvotes: 0

Views: 502

Answers (1)

The fourth bird
The fourth bird

Reputation: 163342

If the string contains only a single dot, you can assert after matching the digits using a positive lookahead (?=\d*\.\d) that there should be a dot followed by a digit at the right.

Note that you can replace with the full match $& instead of using groups.

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

Regex demo

const s = "1000000.12341234";
const regex = /\d(?=\d*\.\d)(?=(?:\d{3})+(?!\d))/g;
console.log(s.replace(regex, "$&,"))

Upvotes: 1

Related Questions