Skip to content

Instantly share code, notes, and snippets.

@grimelda
Last active July 30, 2021 09:19
Show Gist options
  • Save grimelda/08adbebfc5d86d390c2eb5bdb9ad33fd to your computer and use it in GitHub Desktop.
Save grimelda/08adbebfc5d86d390c2eb5bdb9ad33fd to your computer and use it in GitHub Desktop.
Custom google sheets apps script function to reduce value to N significant digits
/**
* @param {A1} value The value which should be reduced to n significant digits. E.g. 668951.12345
* @param {3} nDigits Number of significant digits in cell. Default 3.
* @return The value of a cell with N significant digits. E.g. 669000
* @customfunction
*/
function sigDigits(value, nDigits) {
var value = value || 668951.12345
var nDigits = nDigits || 3
valueRounded = +value.toFixed(0)
lengthRounded = String(valueRounded).length
// Logger.log("Rounded value: "+ valueRounded)
var multiplier = 10**(lengthRounded - nDigits)
// Logger.log("Multiplier for nDigits: "+ multiplier)
value = valueRounded / multiplier
value = +value.toFixed(0)
value = value * multiplier
// Logger.log("Result value: "+ value)
return value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment