Skip to content

Instantly share code, notes, and snippets.

@ashtonmeuser
Last active November 22, 2018 19:09
Show Gist options
  • Select an option

  • Save ashtonmeuser/b29509ff1cd87e0432107f07886d4130 to your computer and use it in GitHub Desktop.

Select an option

Save ashtonmeuser/b29509ff1cd87e0432107f07886d4130 to your computer and use it in GitHub Desktop.
const exponentialPrefix = (value, fixed = 0, unit = '') => {
const prefixes = ['y', 'z', 'a', 'f', 'p', 'n', 'µ', 'm', '', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
const expString = value.toExponential();
const [sig, exp] = expString.split('e').map(Number);
const engr = Math.floor(exp / 3) * 3;
const base = (sig * (10 ** (exp - engr))).toFixed(fixed);
const prefix = prefixes[(engr / 3) + 8];
if (typeof prefix === 'undefined') {
return `${sig.toFixed(fixed)}e${exp}${unit}`;
}
return `${base}${prefix}${unit}`;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment