fix number precision

This commit is contained in:
Philipinho
2026-06-15 01:14:17 +01:00
parent 4b5f42cc9b
commit 6187150224
12 changed files with 152 additions and 33 deletions
+2 -1
View File
@@ -1,4 +1,5 @@
import { makeErrorCell, isErrorCell } from "./error";
import { valueToString } from "./number";
import { MAX_EVAL_DEPTH } from "./types";
import type { FormulaAST, OpCode } from "./ast";
import type { Value, EvalContext } from "./types";
@@ -102,7 +103,7 @@ function evalOp(
switch (op as Exclude<OpCode, "neg" | "not">) {
case "+":
if (typeof a === "string" || typeof b === "string") return (a == null ? "" : String(a)) + (b == null ? "" : String(b));
if (typeof a === "string" || typeof b === "string") return valueToString(a) + valueToString(b);
if (a == null || b == null) return null;
return Number(a) + Number(b);
case "-": return a == null || b == null ? null : Number(a) - Number(b);
@@ -1,4 +1,5 @@
import { register } from "./registry";
import { valueToString } from "../number";
register({
name: "toNumber", arity: { min: 1, max: 1 }, paramTypes: "any", returnType: "number",
@@ -11,6 +12,6 @@ register({
});
register({
name: "toString", arity: { min: 1, max: 1 }, paramTypes: "any", returnType: "string",
eval: ([v]) => v == null ? "" : String(v),
eval: ([v]) => valueToString(v),
doc: "Converts the value to a string.", category: "coercion",
});
@@ -1,6 +1,7 @@
import { register } from "./registry";
import { valueToString } from "../number";
const s = (v: unknown): string => v == null ? "" : String(v);
const s = (v: unknown): string => valueToString(v);
register({
name: "concat", arity: { min: 1, max: null }, paramTypes: "variadic-any", returnType: "string",
@@ -11,3 +11,4 @@ export * from "./format";
export { registry, register } from "./functions/registry";
export type { FormulaFn } from "./functions/registry";
export * from "./graph";
export * from "./number";
@@ -12,3 +12,4 @@ export { registry, register } from "./functions/index";
export type { FormulaFn } from "./functions/index";
export * from "./graph";
export * from "./eval";
export * from "./number";
+10
View File
@@ -0,0 +1,10 @@
export function snapNumber(n: number): number {
if (!Number.isFinite(n)) return n;
return Number(n.toPrecision(15));
}
export function valueToString(v: unknown): string {
if (v == null) return "";
if (typeof v === "number") return String(snapNumber(v));
return String(v);
}