Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What would be the regex to add commas to long digits for legibility?

Tags:

regex

I want to convert 2333444 to 2,333,444, but I'm not clear on how to have the expression work its way from the right to the left as opposed to the other way around. I'm writing Perl, but any regEx syntax is fine, I'll convert it if you are more comfortable with java or javascript.

like image 585
Yevgeny Simkin Avatar asked Dec 05 '25 17:12

Yevgeny Simkin


2 Answers

s/(?<=\d)(?=(\d\d\d)+(?!\d))/,/g
like image 115
Paul van Brenk Avatar answered Dec 08 '25 09:12

Paul van Brenk


Check out Number::Format. This module provides a wide variety of number formatting solutions. e.g. for what you require

  format_number(1234567.89, 2)          

yields '1,234,567.89'

Don't forget that what you're trying to do is locale-specific, and this module will handle that for you. A simple regexp solution won't do that on it's own.

like image 36
Brian Agnew Avatar answered Dec 08 '25 10:12

Brian Agnew