Skip to content

Instantly share code, notes, and snippets.

@ryanvs
Created April 7, 2023 18:31
Show Gist options
  • Save ryanvs/1966877716c6de591621d2195cf97ade to your computer and use it in GitHub Desktop.
Save ryanvs/1966877716c6de591621d2195cf97ade to your computer and use it in GitHub Desktop.
Formatting Exponentials in Javascript
// Formats the value as an exponential as a multiple of 3
// NOTE: The result is a string that is still a valid floating point number
function toTrioExponential(value, fixedDigits)
{
var mag = parseInt(Math.log(Math.abs(value) / Math.LN10);
var rem = mag % 3;
if (rem == 2)
++mag;
else if ((rem == 1) || (rem == -2))
--mag;
else if (rem == -1)
mag -= 2;
var coeff = value * Math.pow(10, -mag);
if (fixedDigits)
return coeff.toFixed(fixedDigits) + "e" + mag.toString();
else
return coeff.toString() + "e" + mag.toString();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment