Created
October 12, 2020 10:02
-
-
Save alanshaw/0e34f8a73b2a98e8c4f43404345cb25a to your computer and use it in GitHub Desktop.
Format a percentage according to some arbitrary rules that actually make it pleasing to look at.
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
// Format a percentage according to some arbitrary rules that actually make it pleasing to look at. | |
// 100 -> 100 // whole numbers have no decimal | |
// 85.1543 -> 85.1 // it just truncates after first non-zero decimal | |
// 3.00345 -> 3.003 // leading zeros preserved before truncate | |
// 3.0000345 -> 3.00003 // ...up to a limit of 5dp | |
// 3.000001 -> 3 // ...so fractional numbers with 5+ leading zeros become an integer | |
function formatPercentage (num) { | |
const [int, frac] = num.toFixed(5).split('.') | |
const index = frac.split('').findIndex(n => n !== '0') | |
return index === -1 ? int : `${int}.${frac.slice(0, index + 1)}` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment