Last active
November 2, 2020 10:35
-
-
Save dejurin/15e7aa25570cff3f1c5ed7654667b830 to your computer and use it in GitHub Desktop.
Round to at most 2 decimal places (only if necessary)
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
// 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