Fix rounding to 0

This commit is contained in:
Codex Agent
2026-03-08 09:35:47 +00:00
parent de3fc810ba
commit 60e462e987
2 changed files with 53 additions and 1 deletions

View File

@@ -10,7 +10,13 @@ export interface SolveResult {
} }
function fmt(n: number): string { function fmt(n: number): string {
return parseFloat(n.toFixed(6)).toString(); if (!Number.isFinite(n)) return n.toString();
if (n === 0) return '0';
if (Math.abs(n) < 1e-6) {
return n.toExponential(6);
}
const rounded = parseFloat(n.toFixed(6));
return rounded.toString();
} }
function gcd(a: number, b: number): number { function gcd(a: number, b: number): number {

View File

@@ -0,0 +1,46 @@
import math
import re
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
CALCULATORS_TS = ROOT / "hdyc-svelte" / "src" / "lib" / "data" / "calculators.ts"
NUMERIC_SAMPLES = [0.1, 0.5, 1, 2, 5, 10, 20, 50, 100]
TARGET_SLUG = "angstroms-to-nautical-miles"
def _parse_factor(slug: str) -> float:
text = CALCULATORS_TS.read_text(encoding="utf-8")
match = re.search(rf'"slug": "{slug}".*?"factor": ([0-9.eE+-]+)', text, flags=re.S)
if not match:
raise AssertionError(f"Could not find calculator definition for '{slug}'")
return float(match.group(1))
def _js_fmt(value: float) -> str:
if not math.isfinite(value):
return str(value)
if value == 0:
return "0"
abs_val = abs(value)
if abs_val < 1e-6:
return f"{value:.6e}"
rounded = float(f"{value:.6f}")
if rounded.is_integer():
return str(int(rounded))
return repr(rounded)
class QuickConversionChartRoundingTests(unittest.TestCase):
def test_angstroms_to_nautical_miles_chart_does_not_round_to_zero(self) -> None:
factor = _parse_factor(TARGET_SLUG)
outputs = [_js_fmt(sample * factor) for sample in NUMERIC_SAMPLES]
self.assertTrue(
any(output != "0" for output in outputs),
f"{TARGET_SLUG} quick conversion chart rounded every sample down to 0: {outputs}",
)
if __name__ == "__main__":
unittest.main()