I want to parse and convert an exponential value into a decimal using JavaScript. 4.65661287307739E-10 should give 0.000000000465661287307739. What
This variant works well for me to display formatted string values for too small/big numbers:
const exponentialToDecimal = exponential => {
let decimal = exponential.toString().toLowerCase();
if (decimal.includes('e+')) {
const exponentialSplitted = decimal.split('e+');
let postfix = '';
for (
let i = 0;
i <
+exponentialSplitted[1] -
(exponentialSplitted[0].includes('.') ? exponentialSplitted[0].split('.')[1].length : 0);
i++
) {
postfix += '0';
}
const addCommas = text => {
let j = 3;
let textLength = text.length;
while (j < textLength) {
text = `${text.slice(0, textLength - j)},${text.slice(textLength - j, textLength)}`;
textLength++;
j += 3 + 1;
}
return text;
};
decimal = addCommas(exponentialSplitted[0].replace('.', '') + postfix);
}
if (decimal.toLowerCase().includes('e-')) {
const exponentialSplitted = decimal.split('e-');
let prefix = '0.';
for (let i = 0; i < +exponentialSplitted[1] - 1; i++) {
prefix += '0';
}
decimal = prefix + exponentialSplitted[0].replace('.', '');
}
return decimal;
};
const result1 = exponentialToDecimal(5.6565e29); // "565,650,000,000,000,000,000,000,000,000"
const result2 = exponentialToDecimal(5.6565e-29); // "0.000000000000000000000000000056565"