Skip to content

[fork-ffi] numbers: toString — Delegates to Lua tostring, which diverges from JS… #96

@Unisay

Description

@Unisay

Package: purescript-lua-numbers
File: src/Data/Number/Format.lua
Function: toString
Class: show-escaping Severity: medium

Delegates to Lua tostring, which diverges from JS Number.prototype.toString in several ways: (1) special values spell as "inf"/"-inf"/"-nan" instead of "Infinity"/"-Infinity"/"NaN"; (2) Lua 5.1 formats with LUAI_NUMFMT = "%.14g", so it loses precision and round-trippability — tostring(0.1+0.2) = "0.3" (JS "0.30000000000000004"), tostring(3.141592653589793) = "3.1415926535898" (JS keeps all 16 digits), and integers above 1e14 collapse to exponential, e.g. tostring(123456789012345.0) = "1.2345678901234e+14" (JS "123456789012345"); (3) large integral values like 1e20 print as "1e+20" rather than the JS expansion "100000000000000000000".

Current (Lua):

toString = (function(num) return tostring(num) end)

Expected: JS toString: shortest round-trippable decimal; "Infinity", "-Infinity", "NaN" for specials; integral Numbers print without a decimal point but with full precision (123456789012345); 0.1+0.2 prints "0.30000000000000004".

Proposed fix:

At minimum special-case the non-finite values and raise the precision to recover round-tripping, e.g.: handle nan -> "NaN", math.huge -> "Infinity", -math.huge -> "-Infinity"; otherwise format finite values with %.17g and trim, or implement a shortest-round-trip routine. A full match of JS toString requires a Grisu/Ryu-style shortest-representation algorithm; %.14g default loss should at least be addressed.

Found by the FFI audit; reproduced under Lua 5.1.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions