When a user enters a number with trailing zeros into Google Sheets, I want the number displayed in the sheet’s cell and the number retrieved via Apps Script to be identical to the number entered. The numbers being entered have a variable number of digits before and after the decimal, e.g. 1.00
,11.00
, 1
, and 11.0
. All need to be displayed and retrieved as entered and as numbers.
The I only way I know how to resolve this is by formatting the value as a string, and then converting it to a number in Apps Script before further processing. I’m trying to avoid formatting numbers as strings to begin with though. Unless I'm missing something, Google Sheets makes this impossible.
How can I keep the variable number of trailing zeroes both in the display of the number and when the number is retrieved via getValue()
in Apps Script? Is there way to do this without formatting as string?
Format options that I’ve tried:
- Automatic and
###
formats will display entry1.00
as1
. ####0.00
and0.00
formats will display entry1
as1.00
.- Scientific formatting will display
1
as1.00E+00
. - Plain text format. I have
=ISNUMBER(myRange)
as a custom data validation formula so it will reject any entry made as plain text. I would rather not drop this validation as these entries must be further processed as numbers. Therefore, I want to ensure that they're numbers upon entry.
For @Kos:
This can be reproduced by executing any of the formatting options that I outlined above. I didn't realize that this needs to be spelled out:
- Open a Google Sheet.
- Click the
Format
menu. - Hover over
Number
. - Click
Custom number format
. - Paste
####0.00
into the entry field. - Click
Apply
. - In the cell that you formatted, enter
1.0
. (Will display as1.00
, which can be expected.) - In Google Apps Script run the following:
function testFormat() {
let sheet = SpreadsheetApp.openById(<your_sheet_id>).getSheetByName(<your_sheet_name>);
let formattedRange = sheet.getRange(<your_cell_row_number>,<your_cell_column_number>,1,1);
Logger.log(formattedRange.getValue())
}
The above will return 1.0
regardless of entering 1.0
or 1.00
.