-
-
Save hideya/0af4be0859ec26f5cc537839339209ad to your computer and use it in GitHub Desktop.
Converts a javascript number from scientific notation to a decimal string
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
function scientificToDecimal(num) { | |
// if the number is in scientific notation remove it | |
if (/\d+\.?\d*e[\+\-]*\d+/i.test(num)) { | |
var zero = '0', | |
parts = String(num).toLowerCase().split('e'), // split into coeff and exponent | |
e = parts.pop(), // store the exponential part | |
l = Math.abs(e), // get the number of zeros | |
sign = e/l, | |
coeff_array = parts[0].split('.'); | |
if (sign === -1) { | |
num = zero + '.' + new Array(l).join(zero) + coeff_array.join(''); | |
} | |
else { | |
var dec = coeff_array[1]; | |
if (dec) l = l - dec.length; | |
num = coeff_array.join('') + new Array(l+1).join(zero); | |
} | |
} | |
return num; | |
}; | |
/* | |
Usage: | |
var converted = scientificToDecimal('2.594e40'); | |
console.log(converted); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment