Skip to content

Instantly share code, notes, and snippets.

@dejurin
Last active November 2, 2020 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dejurin/15e7aa25570cff3f1c5ed7654667b830 to your computer and use it in GitHub Desktop.
Save dejurin/15e7aa25570cff3f1c5ed7654667b830 to your computer and use it in GitHub Desktop.
Round to at most 2 decimal places (only if necessary)
// Solution 1 is to use a script with required rounding algorithm, for example:
// https://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-only-if-necessary
function roundNumber(num, scale) {
if (!(`${num}`).includes('e')) {
return +(`${Math.round(`${num}e+${scale}`)}e-${scale}`);
}
const arr = (`${num}`).split('e');
let sig = '';
if (+arr[1] + scale > 0) {
sig = '+';
}
return +(`${Math.round(`${+arr[0]}e${sig}${+arr[1] + scale}`)}e-${scale}`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment