Skip to content

Instantly share code, notes, and snippets.

@alanshaw
Created October 12, 2020 10:02
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 alanshaw/0e34f8a73b2a98e8c4f43404345cb25a to your computer and use it in GitHub Desktop.
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.
// 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