Search code examples
google-apps-scriptgoogle-sheetsgoogle-sheets-macros

Google App scripts: Unable to preserve Leading zeros since it is automatically removed


I am new to google script. I have a scenario like the below.

I have Sheet1 with Column A and B. Usually I try to store decimal values in to it. I mean integer part in column-A and decimal part in Column-B

For example:

Scenario-1: It the value is 23.75 then Column-A should be 23 and ColumnB would be 75

Scenario-2: If the value is 22.00 then Column-A should be 22 and ColumnB would be 00

I tried like this

 sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
        column = sheet.getRange("B:B");
        column.setNumberFormat("@");
        sRange = "O1:O" + 65;
        cell = sheet.getRange(sRange);
        cell.setValue("00"); 

This works fine for scenario-1, but for scenario-2 it displays only one zero (leading zero is automatically removed). I tried to change the complete column formatting to plain text but no luck. I am strugging to achieve this for the past two days. Any help is greatly appreciated.


Solution

  • Adding an apostrophe:

    cell.setValue("'00");
    

    might be considered adequate.