Skip to content

Commit fb2351f

Browse files
authored
Do not emit a leading zero in floatToGoString exponents >= 10 (#1190)
floatToGoString reproduces Go's strconv.FormatFloat(f, 'g', -1, 64), which pads a float's exponent to a minimum of two digits. The exponent was formatted as 'e+0{dot - 1}', which hard-codes a single leading zero and only produces the right width while dot - 1 is a single digit. Once the exponent reaches two digits (values >= 1e10, whose repr is still plain decimal) it over-pads, e.g. 1e10 became '1e+010' instead of Go's '1e+10'. That affects any emitted sample value or le/quantile bucket boundary at or above 1e10. Use '{dot - 1:02d}' so the exponent is zero-padded to a minimum of two digits and not beyond, matching Go. Add tests/test_utils.py covering both the previously-correct single-digit exponents and the two-digit exponents that regressed. Signed-off-by: Sean Kim <skim8705@gmail.com>
1 parent a39a697 commit fb2351f

2 files changed

Lines changed: 19 additions & 1 deletion

File tree

prometheus_client/utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def floatToGoString(d):
2121
# We only need to care about positive values for le/quantile.
2222
if d > 0 and dot > 6:
2323
mantissa = f'{s[0]}.{s[1:dot]}{s[dot + 1:]}'.rstrip('0.')
24-
return f'{mantissa}e+0{dot - 1}'
24+
return f'{mantissa}e+{dot - 1:02d}'
2525
return s
2626

2727

tests/test_utils.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import unittest
2+
3+
from prometheus_client.utils import floatToGoString
4+
5+
6+
class TestFloatToGoString(unittest.TestCase):
7+
def test_exponent_two_digits_has_no_leading_zero(self):
8+
# floatToGoString mirrors Go's strconv.FormatFloat(f, 'g', -1, 64),
9+
# which pads the exponent to a minimum of two digits. A two-digit
10+
# exponent must not gain a spurious leading zero.
11+
self.assertEqual('1e+10', floatToGoString(1e10))
12+
self.assertEqual('1e+15', floatToGoString(1e15))
13+
self.assertEqual('1.234567890123e+12', floatToGoString(1234567890123.0))
14+
15+
def test_exponent_one_digit_is_zero_padded(self):
16+
# Single-digit exponents keep the two-digit zero padding.
17+
self.assertEqual('1e+06', floatToGoString(1e6))
18+
self.assertEqual('1.234567e+06', floatToGoString(1234567.0))

0 commit comments

Comments
 (0)