Search code examples
google-apps-scripttruncate

Get rid of Negative signs from whole Column


I have a column in which there are some values as $##.00 and some values are -$##.00

What script should I use to convert -$##.00 values to $##.00 values, i.e. converting all numbers to positive?

I tried following that is far from working;

function removNeg(){
  var sheet =SpreadsheetApp.openById('.........');
  var ss = sheet.getSheets()[0];
  var range = ss.getRange("M2:M");
  var values = range.getValues();
  var absValues = Math.abs(values);
  range.setValues(absValues);
}

Solution

    • You want to modify the negative numbers to the positive numbers using Google Apps Script.
    • You want to achieve this at the cells of M2:M.

    If my understanding is correct, how about this answer?

    Modified script:

    When your script is modified, it becomes as follows.

    function removNeg(){
      var sheet =SpreadsheetApp.openById('.........');
      var ss = sheet.getSheets()[0];
      var range = ss.getRange("M2:M");
      var values = range.getValues();
    
      var absValues = values.map(([r]) => [!r || isNaN(r) ? r : Math.abs(r)]);  // Modified
    
      range.setValues(absValues);
    
      // range.setNumberFormats(values.map(([r]) => ["$##.00"]));
    }
    

    Note:

    • If you want to also modify the number format from -$##.00 to $##.00, please use range.setNumberFormats(values.map(([r]) => ["$##.00"])); of the last line.
    • Please use this modified script with enabling V8.

    Reference: