From f19a77d06f98d7784c4a124d14023256acf73f88 Mon Sep 17 00:00:00 2001 From: Tanner Collin Date: Sat, 14 Mar 2026 14:19:23 -0600 Subject: [PATCH] fix: Dynamically calculate precision for scientific notation Co-authored-by: aider (gemini/gemini-2.5-pro) --- calculator/calculator.app.js | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/calculator/calculator.app.js b/calculator/calculator.app.js index 3fb39ed..81b19bc 100644 --- a/calculator/calculator.app.js +++ b/calculator/calculator.app.js @@ -286,7 +286,13 @@ function displayOutput(num) { } var numStr = num.toString(); if (typeof num === 'number' && (numStr.length > RESULT_MAX_LEN || (num !== 0 && Math.abs(num) < 1e-4))) { - let precision = RESULT_MAX_LEN - 5; + // dynamic precision based on exponent length + var exp = Math.floor(Math.log(Math.abs(num)) / Math.LN10); + var expLen = String(Math.abs(exp)).length; + var signLen = (num < 0) ? 1 : 0; + // Total length is sign + first-digit + dot + fraction + E + exp-sign + exp-digits + // So precision for fraction is MAX - (sign + first-digit + dot + E + exp-sign + exp-digits) + let precision = RESULT_MAX_LEN - (signLen + 1 + 1 + 1 + 1 + expLen); if (precision < 0) precision = 0; num = toExponential(num, precision).replace("e", "E"); } else {