Skip to content

Instantly share code, notes, and snippets.

@andrewroberts
Created February 14, 2020 07:26
Show Gist options
  • Save andrewroberts/ef2be648b02e9cfcfc34d45bc2283328 to your computer and use it in GitHub Desktop.
Save andrewroberts/ef2be648b02e9cfcfc34d45bc2283328 to your computer and use it in GitHub Desktop.
JavaScript function to format various value types as a string.
function testNumber() {
var value = 1234.56789
var a = format(value, {numberOfDecimalPlaces: 2})
debugger
}
function testDate() {
var value = new Date()
var a = format(value)
debugger
}
function testObject() {
var value = {a: 1, b: 2}
var a = format(value)
debugger
}
/**
* Format an object into a suitable value
*
* @param {object} value
* @param {object} options
* {number} numberOfDecimalPlaces [OPTIONAL, DEFAULT: 0]
* {string} dateFormat [OPTIONAL, DEFAULT: 'yyyy-MM-dd']
*
* @return {string} formattedValue
*/
function formatString(value, options) {
var formattedValue = value
options = options || {}
if (typeof value === 'number') {
var placeholder = '%s'
var numberOfDecimalPlaces = 0
if (options.numberOfDecimalPlaces !== undefined) {
numberOfDecimalPlaces = options.numberOfDecimalPlaces
}
if (numberOfDecimalPlaces > 0) {
placeholder = '%.' + numberOfDecimalPlaces + 'f'
}
var multiplier = Math.pow(10, numberOfDecimalPlaces)
formattedValue = Utilities.formatString(placeholder, Math.round(value * multiplier) / multiplier)
} else if (value instanceof Date) {
var timeZone = Session.getScriptTimeZone()
var dateFormat = 'yyyy-MM-dd'
if (options.dateFormat !== undefined) {
dateFormat = options.dateFormat
}
formattedValue = Utilities.formatDate(value, timeZone, dateFormat)
} else if (typeof value === 'object') {
formattedValue = JSON.stringify(value)
}
return formattedValue
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment