Skip to content

Bug: std.format %g precision threshold and zero handling #890

Description

@He-Pin

Description

The %g format specifier in std.format has two bugs related to precision handling. According to the Jsonnet documentation, std.format should follow Python's % formatting rules.

Bug 1: Incorrect threshold for exponential notation

Expected behavior: When the exponent equals the precision, %g should use exponential notation.

Test case:

std.format("%.6g", [1e6])

Python reference:

>>> "%.6g" % 1e6
'1e+06'

go-jsonnet output: "1000000" (incorrect - uses fixed-point notation)

Expected output: "1e+06" (exponential notation)

The threshold should be exponent >= precision, not exponent > precision.

Bug 2: Incorrect zero handling with precision 0

Expected behavior: When formatting 0.0 with precision 0 using %g, the output should be "0", not "0e+00".

Test case:

std.format("%.0g", [0.0])

Python reference:

>>> "%.0g" % 0.0
'0'

go-jsonnet output: "0e+00" (incorrect)

Expected output: "0"

Additional test cases

// Bug 1: threshold tests
std.format("%.1g", [10])      // Expected: "1e+01", go-jsonnet: "10"
std.format("%.2g", [100])     // Expected: "1e+02", go-jsonnet: "100"
std.format("%.3g", [1000])    // Expected: "1e+03", go-jsonnet: "1000"

// Bug 2: zero with different precisions
std.format("%.0g", [0.0])     // Expected: "0", go-jsonnet: "0e+00"
std.format("%.1g", [0.0])     // Expected: "0", go-jsonnet: "0e+00"

Verification

All test cases have been verified against Python 3's % operator, which is the reference implementation according to the Jsonnet specification.

Impact

These bugs affect compatibility with Python's formatting behavior, which is the documented standard for std.format.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions