From 555ee9d65d1b2f08c6b152adc37faa9479fec5e7 Mon Sep 17 00:00:00 2001 From: Sean Kim Date: Thu, 9 Jul 2026 18:14:58 -0700 Subject: [PATCH] Do not emit a leading zero in floatToGoString exponents >= 10 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 --- prometheus_client/utils.py | 2 +- tests/test_utils.py | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 tests/test_utils.py diff --git a/prometheus_client/utils.py b/prometheus_client/utils.py index 87b75ca8..52c852ab 100644 --- a/prometheus_client/utils.py +++ b/prometheus_client/utils.py @@ -21,7 +21,7 @@ def floatToGoString(d): # We only need to care about positive values for le/quantile. if d > 0 and dot > 6: mantissa = f'{s[0]}.{s[1:dot]}{s[dot + 1:]}'.rstrip('0.') - return f'{mantissa}e+0{dot - 1}' + return f'{mantissa}e+{dot - 1:02d}' return s diff --git a/tests/test_utils.py b/tests/test_utils.py new file mode 100644 index 00000000..50eac33c --- /dev/null +++ b/tests/test_utils.py @@ -0,0 +1,18 @@ +import unittest + +from prometheus_client.utils import floatToGoString + + +class TestFloatToGoString(unittest.TestCase): + def test_exponent_two_digits_has_no_leading_zero(self): + # floatToGoString mirrors Go's strconv.FormatFloat(f, 'g', -1, 64), + # which pads the exponent to a minimum of two digits. A two-digit + # exponent must not gain a spurious leading zero. + self.assertEqual('1e+10', floatToGoString(1e10)) + self.assertEqual('1e+15', floatToGoString(1e15)) + self.assertEqual('1.234567890123e+12', floatToGoString(1234567890123.0)) + + def test_exponent_one_digit_is_zero_padded(self): + # Single-digit exponents keep the two-digit zero padding. + self.assertEqual('1e+06', floatToGoString(1e6)) + self.assertEqual('1.234567e+06', floatToGoString(1234567.0))