opa
opa copied to clipboard
sprintf: fix number formatting quirks wrt float/int
$ opa eval -fpretty 'sprintf("%f", [13])'
"%!f(int=13)"
This should output "13". Using %v is a workaround, but won't allow us to control the number of digits after the dot, like %.3f would allow.
The problem is this code: https://github.com/open-policy-agent/opa/blob/v0.39.0/topdown/strings.go#L427-L436
☝️ We're trying to find the best format of the arg to pass along to the golang stdlib Printf function. The heuristic breaks down when you try to format a number that could be an int or a float internally.
Here's another example:
$ opa eval -fpretty --import future.keywords '{ sprintf("%f", [x]) | some x in {1, 1.1}}'
[
"%!f(int=1)",
"1.100000"
]
The desired output would be [ "1", "1.100000"].
💭 One approach would be to examine the format string, and prepare the number argument accordingly: If the n-th format specifier is of the float-y type, make the n-th arg a float; if it's int-y, make it an int.
I'd like to take a stab at completing this! Please assign it to me.
Thanks! LMK if you need assistance or if something is unclear or if you'd like to discuss some approach... 😃
Question: @srenatus Let's say I set the format to %.3f in the example you've shown above. Would this be the expected output?
$ opa eval -fpretty --import future.keywords '{ sprintf("%.3f", [x]) | some x in {1, 1.1}}'
[
"001",
"1.100"
]
OR would you prefer to see the exact same with the int value?
$ opa eval -fpretty --import future.keywords '{ sprintf("%.3f", [x]) | some x in {1, 1.1}}'
[
"1",
"1.100"
]
Hmm I think I'd go with "1.000". Like here, https://go.dev/play/p/tNR1eM9TpSD
Hi there, should we reopen this issue since the fix has been reverted? https://github.com/open-policy-agent/opa/pull/4794
Or is there another issue I should watch to track a fix for this behaviour?
Edit: maybe https://github.com/open-policy-agent/opa/issues/4771 is what I'm missing, apologies
Yeah that other issue is what to watch now. We could reopen this one, anyways, you're right.
Is there any update on this? Just got bit by this recently.
Nope, no work has happened on this since, AFAICT 😓