google / google/go-jsonnet

std.format %g produces wrong output for small numbers

Open
#888 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
1.8k
Forks
263
PR merge metrics
No merged PRs in 30d

Description

## Summary

`%g` format specifier produces incorrect output for small decimal numbers. The precision parameter (number of significant digits) is not properly applied when the number has leading zeros after the decimal point.

## Reproduction

```
$ go-jsonnet -e '"%.3g" % 0.001234'
"0"

$ go-jsonnet -e '"%.4g" % 0.001234'
"0.001"

$ go-jsonnet -e '"%g" % 0.001234'
"0.00123"
```

## Expected (Python reference)

```python
>>> "%.3g" % 0.001234
'0.00123'
>>> "%.4g" % 0.001234
'0.001234'
>>> "%g" % 0.001234
'0.001234'
```

## Analysis

The issue appears to be in the `%g` format implementation when the number is in the fixed-point range (exponent >= -4). The precision specifies significant digits, but the implementation seems to not correctly account for leading zeros when calculating the number of fractional digits needed.

For example, `0.001234` has exponent -3, which is >= -4 (fixed-point range). With precision 3, the output should have 3 significant digits: `0.00123` (1.23 × 10⁻³). Instead, go-jsonnet outputs `"0"`.

The same issue affects `%#g` (alternate flag) with small numbers:

```
$ go-jsonnet -e '"%#g" % 0.0001'
"0.00010"
```

Expected: `"0.000100000"` (6 significant digits with trailing zeros preserved)

## Version

go-jsonnet v0.22.0

Contributor guide

Open the contributing guide

Research direction

Start by locating the go-jsonnet std.format implementation for the %g and %#g specifiers, then run the reproduction commands from the issue with precisions 3, 4, and the default. Done means small fixed-point values use the requested significant digits and %#g preserves the expected trailing zeros without regressing the other examples.

Written by the indexing model from the issue text.

Assessment

Tech stack
go
Domain
cli
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Clearly specified
Newbie friendliness
68/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.