iJay
iJay

Reputation: 4283

Difference between getValue() and getDisplayValue() on google app script

What is the difference of range.getDisplayValue() and range.getValue() on Google Apps Script?

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var val1 = sheet.getRange(7,5).getDisplayValue();
var val2 = sheet.getRange(7,5).getValue();

Val1 and Val2 are both same.

Upvotes: 18

Views: 55344

Answers (3)

Marios
Marios

Reputation: 27380

To elaborate more on the accepted answer.

According to the official documentation.

getDisplayValue():

Returns the displayed value of the top-left cell in the range. The value is a String. The displayed value takes into account date, time and currency formatting formatting, including formats applied automatically by the spreadsheet's locale setting. Empty cells return an empty string.

getValue():

Returns the value of the top-left cell in the range. The value may be of type Number, Boolean, Date, or String depending on the value of the cell. Empty cells return an empty string.

Frequently asked questions in stackoverflow - use cases:

  • A valid date object in a sheet would return a date object when using getValue but a string (respecting the format) when using getDisplayValue.
  • A valid boolean value in google sheets (TRUE, FALSE) would return true, false boolean JavaScript objects when using getValue but strings when using getDisplayValue. This becomes quite handy when you want you use if conditions. You can simply use the object itself if(sheet.getRange('A1').getValue()) if A1 contains a boolean value.

Upvotes: 2

SangyK
SangyK

Reputation: 839

To add more to Henrique's explanation, here is an example from my experience.

I have a column where I enter time in IST

IST     
--------
2:00 AM 

And when I get the value of that column using,

var myTime = range.getValue();

which actually returned,

Sat Dec 30 1899 01:36:40 GMT+0530 (IST)

But range.getDisplayValue() solved my problem which returned what I have entered, 2:00 AM.

Upvotes: 10

Henrique G. Abreu
Henrique G. Abreu

Reputation: 17772

getDisplayValue returns the value as you see in the screen, therefore always a string, while getValue returns the value underneath, therefore an object. Which may be a string if the range has text in it.

The difference is more clear if the range has numbers or dates in it. Specially if the spreadsheet locale formats the numbers with commas as decimal separators or if you set custom formats in your ranges.

Upvotes: 23

Related Questions