Skip to content

Instantly share code, notes, and snippets.

@superstes
Created April 24, 2024 21:03
Show Gist options
  • Save superstes/bff0ce749f861b9c0f8b5df98352988b to your computer and use it in GitHub Desktop.
Save superstes/bff0ce749f861b9c0f8b5df98352988b to your computer and use it in GitHub Desktop.
Javascript - round number to N decimal places
/*
NOTES:
not totally exact. if you need consistent rounding on a high degree - search further
see also: https://stackoverflow.com/questions/11832914/how-to-round-to-at-most-2-decimal-places-if-necessary
*/
const DECIMAL_MUL = {
1: 10,
2: 100,
3: 1000,
4: 10000,
5: 100000,
}
function RoundToDecimals(dec, num) {
let mul = DECIMAL_MUL[dec];
return Math.round((num + Number.EPSILON) * mul) / mul;
}
RoundToDecimals(2, 2.49884444) # 2.49
RoundToDecimals(4, 98.349237482) # 98.3492
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment