Skip to main content
Participant
November 22, 2023
Question

Need help with this Script for US currency formatting

  • November 22, 2023
  • 1 reply
  • 252 views

This is the task I've been assigned:

Create a script that will take numbers from certain data fields and format them into US currency. This action is to trigger after all variable fields have been populated. For example, this:

Figure A.

to this:

Figure B.

 

I'm not a coder. As such I've turn to AI tools to help me along. So far I've gotten this far:

Figure C.

This is my working code that's getting me figure C results:

Figure D.

// Check if InDesign application is running
if (app && app.name === "Adobe InDesign" && app.version >= "18.5") {
  // Define the GREP Find/Change parameters
  var findGrepOptions = app.findGrepPreferences;
  var changeGrepOptions = app.changeGrepPreferences;

  // Define the regular expression pattern to match numbers with optional commas and currency symbols
  var currencyPattern = "[$,]";
  var numberPattern = "\\b(\\d+(\\.\\d{2})?)\\b"; // Matches numbers with optional two decimal places, using word boundaries

  // Set the find and change properties to strip out commas and currency symbols
  findGrepOptions.findWhat = currencyPattern;
  changeGrepOptions.changeTo = "";

  // Perform the Find/Change operation to strip out commas and currency symbols
  app.activeDocument.changeGrep();

  // Set the find properties for numbers to be converted to US currency format
  findGrepOptions.findWhat = numberPattern;

  // Find all instances of the numbers
  var foundItems = app.activeDocument.findGrep();

  // Define a function to ignore numbers already formatted properly
  function isFormattedProperly(match) {
    return match.toString().indexOf("$") === -1; // Ignore if already formatted as US currency
  }

  // Loop through found items and change them to US currency format
  for (var i = 0; i < foundItems.length; i++) {
    if (isFormattedProperly(foundItems[i])) {
      foundItems[i].contents = "$" + Number(foundItems[i].contents).toFixed(2);
    }
  }

  // Reset the Find/Change preferences
  findGrepOptions = NothingEnum.NOTHING;
  changeGrepOptions = NothingEnum.NOTHING;

  alert("Number formats have been converted to US Currency format.");
} else {
  alert("Adobe InDesign 18.5 or later is required to run this script.");
}

  

So what do I need to change so I can get the results of figure A?

 

Any help is greatly appreciated.

This topic has been closed for replies.

1 reply

James Gifford—NitroPress
Legend
November 22, 2023

Not a scripter, but from other coding experience you may need to 'escape' the commas so they aren't interpreted as code, but as content.