diff --git a/calculator/calculator.app.js b/calculator/calculator.app.js index 77bf8e7..acef778 100644 --- a/calculator/calculator.app.js +++ b/calculator/calculator.app.js @@ -206,6 +206,29 @@ function subtract(x, y) { return sum(x, -y); } +function toExponential(num, precision) { + if (num === 0) { + let z = "0"; + if (precision > 0) z += "." + "0".repeat(precision); + return z + "e+0"; + } + var sign = ""; + if (num < 0) { + sign = "-"; + num = -num; + } + var exp = Math.floor(Math.log10(num)); + var mantissa = num / Math.pow(10, exp); + + var mantissaFixed = mantissa.toFixed(precision); + if (parseFloat(mantissaFixed) >= 10) { + mantissaFixed = (mantissa/10).toFixed(precision); + exp++; + } + + return sign + mantissaFixed + "e" + (exp >= 0 ? "+" : "") + exp; +} + function fixFloat(n) { if (Math.abs(n) < 1e-10) return 0; return n; @@ -265,7 +288,7 @@ function displayOutput(num) { if (typeof num === 'number' && (numStr.length > RESULT_MAX_LEN || (num !== 0 && Math.abs(num) < 1e-4))) { let precision = RESULT_MAX_LEN - 8; if (precision < 0) precision = 0; - num = num.toExponential(precision).replace("e", "E"); + num = toExponential(num, precision).replace("e", "E"); } else { num = numStr; }