Skip to content

Instantly share code, notes, and snippets.

@michaelblyons
Last active August 29, 2015 14:06
Show Gist options
  • Save michaelblyons/69f735e5ce6dc15f56a7 to your computer and use it in GitHub Desktop.
Save michaelblyons/69f735e5ce6dc15f56a7 to your computer and use it in GitHub Desktop.
Make a number into rounded text in quasi-engineering notation. Idea taken from Facebook Like count display.
function bigRound(num, prcn) {
if (num < 1000) {
return num;
};
var rndup = 0.000001;
var sfxs = ['k', 'M', 'B', 'T', 'Q'];
var expt = Math.floor(Math.log(num) / Math.LN10 + rndup);
var sfx = sfxs[Math.floor(expt / 3) - 1];
var clip = +(num * 1.0 / Math.pow(10, expt - expt % 3)).toPrecision(prcn || 2);
return clip + sfx;
}
@michaelblyons
Copy link
Author

rndup fixes a javascript float-representation rounding error.

@michaelblyons
Copy link
Author

Possible future enhancement: small numbers as well, but this would make it kind of clunky to use B for billion, T for trillion, and up instead of their real metric prefixes.

[ ... , 'n', 'μ', 'm', '', 'k', 'M', 'G', ... ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment