Implement Number.toFixed (#1413) · TypeScriptToLua/TypeScriptToLua@2dfca0b · GitHub
Skip to content

Commit 2dfca0b

Browse files
authored
Implement Number.toFixed (#1413)
1 parent 1af3db3 commit 2dfca0b

4 files changed

Lines changed: 37 additions & 0 deletions

File tree

‎src/LuaLib.ts‎

Lines changed: 1 addition & 0 deletions

‎src/lualib/NumberToFixed.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
/// https://www.ecma-international.org/ecma-262/10.0/index.html#sec-number.prototype.tofixed
2+
export function __TS__NumberToFixed(this: number, fractionDigits?: number): string {
3+
if (Math.abs(this) >= 1e21 || this !== this) {
4+
return this.toString();
5+
}
6+
const f = Math.floor(fractionDigits ?? 0);
7+
// reduced to 99 as string.format only supports 2-digit numbers
8+
if (f < 0 || f > 99) {
9+
throw "toFixed() digits argument must be between 0 and 99";
10+
}
11+
// throws "invalid format (width or precision too long)" if strlen > 99
12+
// if (f < 80) return fmt; else try {return fmt} catch(_) { throw "toFixed() digits argument..." }
13+
return string.format(`%.${f}f`, this);
14+
}

‎src/transformation/builtins/number.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ export function transformNumberPrototypeCall(
2020
return params.length === 0
2121
? lua.createCallExpression(lua.createIdentifier("tostring"), [caller], node)
2222
: transformLuaLibFunction(context, LuaLibFeature.NumberToString, node, caller, ...params);
23+
case "toFixed":
24+
return transformLuaLibFunction(context, LuaLibFeature.NumberToFixed, node, caller, ...params);
2325
default:
2426
context.diagnostics.push(unsupportedProperty(calledMethod.name, "number", expressionName));
2527
}

‎test/unit/builtins/numbers.spec.ts‎

Lines changed: 20 additions & 0 deletions

0 commit comments

Comments
 (0)