Skip to content

fix: std.format accepts boolean for numeric conversion codes#1328

Open
He-Pin wants to merge 1 commit into
google:masterfrom
He-Pin:fix-format-boolean-coercion
Open

fix: std.format accepts boolean for numeric conversion codes#1328
He-Pin wants to merge 1 commit into
google:masterfrom
He-Pin:fix-format-boolean-coercion

Conversation

@He-Pin

@He-Pin He-Pin commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

Summary

The official Jsonnet spec states:

The string formatting follows the same rules as Python.

In Python, bool is a subclass of int, so "%d" % True returns "1". However, jsonnet currently rejects booleans for all numeric conversion codes with Format required number at N, got boolean.

This fix coerces boolean values to 0/1 at the top of format_code() (after the %s branch, which correctly passes booleans through std.toString), matching Python's behavior.

Before / After

Expression Python jsonnet (before) jsonnet (after)
"%d" % true "1" ERROR "1"
"%d" % false "0" ERROR "0"
"%f" % true "1.000000" ERROR "1.000000"
"%f" % false "0.000000" ERROR "0.000000"
"%x" % true "1" ERROR "1"
"%o" % true "1" ERROR "1"
"%e" % true "1.000000e+00" ERROR "1.000000e+00"
"%g" % true "1" ERROR "1"
"%c" % true "\x01" ERROR "\x01"
"%s" % true "True" "true" "true"

Changes

  • stdlib/std.jsonnet: In format_code(), handle %s first with the original value, then coerce booleans to 0/1 via local num_val = if std.type(val) == 'boolean' then (if val then 1 else 0) else val; for all numeric conversion codes (%d, %o, %x, %f, %e, %g, %c).
  • test_suite/format.jsonnet: Added assertions for %d, %f, %x, %o, %e, %g, %s with boolean values.

Test plan

  • Added assertions for %d, %f, %x, %o, %e, %g with boolean values
  • %s with boolean continues to produce "true" / "false" (unchanged)
  • Existing tests for numeric and string values remain passing

@google-cla

google-cla Bot commented Jun 26, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

The official Jsonnet spec states that std.format follows Python's
string formatting rules. In Python, bool is a subclass of int, so
"%d" % True returns "1". This fix coerces boolean values to 0/1
before processing numeric conversion codes, matching Python's behavior.
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.

1 participant