Skip to content

Keep full precision for non-integer numbers in jq output#255

Open
sueun-dev wants to merge 1 commit into
cli:trunkfrom
sueun-dev:fix-jq-float-precision
Open

Keep full precision for non-integer numbers in jq output#255
sueun-dev wants to merge 1 commit into
cli:trunkfrom
sueun-dev:fix-jq-float-precision

Conversation

@sueun-dev

Copy link
Copy Markdown

jq.Evaluate rounds non-integer numbers to two decimal places, so the output loses precision and can even turn a nonzero value into zero.

For input {"pi": 3.14159, "small": 0.001, "big": 123456.789}, evaluating .pi, .small, .big prints:

3.14
0.00
123456.79

jsonScalarToString formats non-integer float64 values with strconv.FormatFloat(tt, 'f', 2, 64). The package doc says scalars are written "similar to how jq --raw works", but jq prints 3.14159, 0.001, and 123456.789. The 0.001 -> 0.00 case is the worst one, since a nonzero number renders as zero.

The non-integer branch now uses precision -1, the shortest string that round-trips the float64, so the three values above print exactly as jq does. The integer-valued branch is unchanged, so whole numbers still print without a trailing .0.

Added a case to TestEvaluateFormatted covering 3.14159, 0.001, and 123456.789. It fails on the current code and passes with the change. go test ./..., go vet, and gofmt -l are clean.

jsonScalarToString formatted non-integer float64 values with two
decimal places, so jq.Evaluate truncated them: 3.14159 became 3.14
and 0.001 became 0.00. That contradicts the package's documented
behavior of writing values 'similar to how jq --raw works', and the
0.001 -> 0.00 case turns a nonzero value into zero.

Use FormatFloat with precision -1, which produces the shortest string
that round-trips the float64. Integer-valued floats are unchanged.
@sueun-dev sueun-dev requested a review from a team as a code owner June 23, 2026 00:37
@sueun-dev sueun-dev requested review from BagToad and removed request for a team June 23, 2026 00:37
@babakks

babakks commented Jun 23, 2026

Copy link
Copy Markdown
Member

Thanks for flagging this, @sueun-dev! 🙏

Can you please open an issue first, so that we can have a thread to discuss this?

@sueun-dev

Copy link
Copy Markdown
Author

thanks @babakks! opened #256 for the discussion. happy to move the conversation there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants