2

What is the correct string formatting structure for Google Apps Scripts - as per the documentation.

Is this about how C formatting works?

I cannot figure how to write sprintf-like string formatting using '%'-style format strings.

I am using Google Apps Scripts to copy data from a spreadsheet, process the data in memory, then replace text placeholders in a Google Doc with the processed data.

Some of the data includes numbers, intended to represent currency, and these are placed into tables.

I have written a simple function to format the strings...

function formatStringCurrency(tempValue) {
  // Description
  return Utilities.formatString("$%d,%3.2f", tempValue/1000, tempValue%1000);
}

and I parse the necessary data through this function to prepare a "currency-like" string.

My problem - my formatting function works perfectly unless the string is over 1,000, and is also a multiple of 1000, that is, does not contain hundreds or less.

For example, here is a screenshot sample of my current output...

spreadsheet output: first row $2,325.00, $9,300.00, second row $3,0.00, $12,0.00, etc...

The second row is intended to display $3,000.00 and $12,000.00.

I have thought about formatting the Google Doc table, however that is not yet possible either manually or programmatically.

I have also attempted to remove all formatting from the numbers as they are represented in the original spreadsheet, however this does not make a difference.

As always, any assistance would be appreciated.

1 Answer 1

2

Leading zeros (zeros in the left till have a minimum number of digits) don't work for floats. But this will work

function formatStringCurrency(tempValue) {
  // Description
  return Utilities.formatString("$%d,%02d%1.2f", tempValue/1000, tempValue%1000/10,tempValue%10);
}

function examples(){
  Logger.log(formatStringCurrency(1));
  Logger.log(formatStringCurrency(0.1));
  Logger.log(formatStringCurrency(1000));
  Logger.log(formatStringCurrency(100));
  Logger.log(formatStringCurrency(134141));
  Logger.log(formatStringCurrency(32423.43));
}

result:

[14-07-08 19:47:21:138 HKT] $0,001.00
[14-07-08 19:47:21:141 HKT] $0,000.10
[14-07-08 19:47:21:145 HKT] $1,000.00
[14-07-08 19:47:21:149 HKT] $0,100.00
[14-07-08 19:47:21:154 HKT] $134,141.00
[14-07-08 19:47:21:157 HKT] $32,423.43
0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.