Created
June 22, 2021 09:24
-
-
Save dgg/7cd637fbd0c8a54693a5b4446e20a9d9 to your computer and use it in GitHub Desktop.
rounding a number in typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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