/** Format a number as a MATLAB literal that round-trips exactly and reads well. */ export function formatNumber(x: number): string { if (!Number.isFinite(x)) return x > 0 ? "Inf" : x < 0 ? "-Inf" : "NaN"; if (x === 0) return "0"; const ax = Math.abs(x); if (Number.isInteger(x) && ax < 1e6) return String(x); if (ax >= 1e5 || ax < 1e-4) { // shortest exponential form that round-trips, written like 200e9 rather than 2e+11 for (let p = 0; p <= 16; p++) { const s = x.toExponential(p); if (Number(s) === x) return tidyExponential(s); } return tidyExponential(x.toExponential()); } return String(x); } function tidyExponential(s: string): string { const [mant, expo] = s.split("e"); const e = Number(expo); // Prefer engineering-style exponents (multiples of 3) when the mantissa stays short const shift = ((e % 3) + 3) % 3; if (shift !== 0) { const mNum = Number(mant) * Math.pow(10, shift); const mStr = String(Number(mNum.toPrecision(15))); if (mStr.length <= 8) return `${mStr}e${e - shift}`; } return `${mant}e${e}`; } export function formatString(s: string): string { return `'${s.replace(/'/g, "''")}'`; } export function formatVector(v: readonly number[]): string { return `[${v.map(formatNumber).join(" ")}]`; }