Skip to content

Instantly share code, notes, and snippets.

@hideya
Forked from jiggzson/scientificToDecimal.js
Last active February 3, 2019 14:36
Show Gist options
  • Save hideya/0af4be0859ec26f5cc537839339209ad to your computer and use it in GitHub Desktop.
Save hideya/0af4be0859ec26f5cc537839339209ad to your computer and use it in GitHub Desktop.
Converts a javascript number from scientific notation to a decimal string
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