Skip to content

Instantly share code, notes, and snippets.

@Narshe1412
Created February 17, 2020 12:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Narshe1412/838c5f0e1582bca0a023dfcc44c05fe4 to your computer and use it in GitHub Desktop.
Save Narshe1412/838c5f0e1582bca0a023dfcc44c05fe4 to your computer and use it in GitHub Desktop.
TypeScript round function with a default return value if the object provided is not defined or not a number
/**
* Given an object with a property, it tests if the property is a number and returns the round of that
* Otherwise returns the value provided by defaultValue, or null
* @param obj The object that contains the property to test
* @param prop The property that will be tested
* @param decimalsToRound The number of decimals to round to
* @param defaultValue The default value provided if it cannot complete the transaction
*/
export const roundOrDefault = (obj: any, prop: string, decimalsToRound: number, defaultValue = null) => {
if (!obj) {
return defaultValue;
}
if (obj && !obj.hasOwnProperty(prop)) {
return defaultValue;
}
if (obj && obj.hasOwnProperty(prop)) {
if (typeof obj[prop] !== 'number') {
return defaultValue;
} else {
return Math.round(obj[prop] * 10 ** decimalsToRound) / 10 ** decimalsToRound;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment