Members Only

Inserting Commas in Large Numbers Using GREP

Use this quick solution when you need to add commas to lots of numbers in InDesign.

Question: “I have an InDesign file with lots of tables with numbers. The client sent data/numbers without commas, but now they are asking that commas be included. Is there a GREP code to insert commas in numerals where needed? For example, I need to update 25309 to 25,309 and 856194 to 856,194.”

Answer: Yes, there is! You can do it quite simply, using multiple rounds of Find/Replace with GREP. Here’s how it works:

Round 1: Insert the Thousands Comma

For the first pass, we’ll insert the thousands comma in every number with four or more digits, so in Find What we want to match the last three digits of the number only if they are preceded by another digit (e.g., 1234 but not 123) and we want GREP to remember those three digits so we don’t lose them. The code for that is:

(?<=\d)(\d{3})$

$ matches “end of paragraph,”

\d{3} matches 3 digits (we place them in parentheses in the full expression because we want InDesign to remember them for the next step)

(?<=\d) says “Look behind to see if there’s a digit there.”

Copy and paste the code into the Find What field.

In the Change To field, copy and paste this code: ,$1

which means “insert a comma, then the content we found and saved (those last three digits).”

Here’s the before and after, side by side, with a thousands comma inserted everywhere it’s needed.
style=”font-size: revert; color: initial;”> 

Round 2, 3, 4, etc.

Now we want to look for 4 digits in a row followed by a comma (e.g., 1234,567) and insert another comma after the first one (1,234,567).

The Find What expression is: (\d)(\d{3},)

In this expression, (\d) matches any single digit and saves its value, and (\d{3},) matches three digits followed by a comma and saves the digits and comma. The whole expression will be matched only if there are four consecutive digits before a comma and there is no comma between the first and second digits.

The Change To expression is: $1,$2

Like in Round 1, $1 is the first saved match (first digit of four) and $2 is the second saved match (the last three digits plus the comma).

Run this as many times as you need to, until it can’t find any more.

Here’s the before and after of one round. Notice that there’s still a missing comma in that last line:

You just run the exact same Find/Change again to insert the “billions comma,” again to insert a “trillions comma,” and so on.

This article from CreativePro Magazine is for members only. To continue reading, please log in above, or sign up for a membership today! Thanks for supporting CreativePro!

Bookmark
Please login to bookmark Close

Not a member yet?

Get unlimited access to articles and member-only resources with a CreativePro membership.

Become a Member

Comments (8)

Leave a Reply

Your email address will not be published. Required fields are marked *

Loading comments...