Created
April 7, 2023 18:31
-
-
Save ryanvs/1966877716c6de591621d2195cf97ade to your computer and use it in GitHub Desktop.
Formatting Exponentials in Javascript
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
// 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