Skip to content

Instantly share code, notes, and snippets.

@dgg
Created June 22, 2021 09:24
Show Gist options
  • Save dgg/7cd637fbd0c8a54693a5b4446e20a9d9 to your computer and use it in GitHub Desktop.
Save dgg/7cd637fbd0c8a54693a5b4446e20a9d9 to your computer and use it in GitHub Desktop.
rounding a number in typescript
export const DECIMAL_PLACES = 1
// it may have some rounding problems in some cases, but we should be good
export const round = (n: number, decimals: number = DECIMAL_PLACES): number => {
const abs = n < 0 ? Math.abs(n) : n
const factorOfTen = Math.pow(10, decimals)
const rounded = Math.round(abs * factorOfTen) / factorOfTen
const result = abs === n ? rounded : -rounded
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment