Search code examples
google-apps-scriptgoogle-sheetscurrency-formatting

Format a number with many decimal places as currency


I have this script that sends an email with a specific value of a cell in a spreadsheet.

function sendNotification() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var cell = ss.getActiveCell().getA1Notation();
  var cellvalue = ss.getActiveCell().getValue().toString();
  var spr = SpreadsheetApp.getActiveSpreadsheet();
  var column = spr.getRange('k2');
  var values = column.getValues();
  var cell = sheet.getRange('k2');
  cell.setNumberFormat("$0.00");
  var range_bill_com = sheet.getRange('k2');
  if (range_bill_com.getValue() !=-1){
     var recipients = "[email protected]";
     var message = '';
     var subject = 'exemplo';
     var body = 'O valor previsto de Lucro/Prejuízo para hoje é de:' + values;
     MailApp.sendEmail(recipients, subject, body);
        }
  };

But in the email received, the format of this value is not the same as I would like , that would be in US dollars (ex: "O valor previsto de Lucro/Prejuízopara hoje é de:945.2709034832405). I tried some changes , but do not know how to get the message value in the format I want. Can anyone help me change this script?


Solution

  • First trim the number of decimal places, then concatenate text with a leading dollar sign.

    function sendNotification() {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = ss.getActiveSheet();
      var cell = ss.getActiveCell().getA1Notation();
      var cellvalue = ss.getActiveCell().getValue().toString();
    
      var column = ss.getRange('k2');
      var value = column.getValue();
      var cell = sheet.getRange('k2');
      cell.setNumberFormat("$0.00");
    
      var range_bill_com = sheet.getRange('k2');
    
      if (range_bill_com.getValue() !=-1){
        var recipients = "[email protected]";
        var message = '';
        var subject = 'exemplo';
        var valueFormatedAsCurrency = formatToCurrency(value);
        var body = 'O valor previsto de Lucro/Prejuízo para hoje é de:' + 
          valueFormatedAsCurrency;
        MailApp.sendEmail(recipients, subject, body);
      }
    };
    
    function formatToCurrency(inputArg) {
      //Logger.log('typeof inputArg: ' + typeof inputArg);
    
      var inputToNumber = Number(inputArg);
      var fixedValue = inputToNumber.toFixed(2);
    
      var valAsString = fixedValue.toString();
      //Logger.log('typeof valAsString: ' + typeof valAsString);
    
      var valAsCurrency = "$" + valAsString;
    
      //Logger.log('valAsCurrency: ' + valAsCurrency);
      return valAsCurrency;
    };