From a5f31d6eaa38b47ccd965a0009ebb9521835aa81 Mon Sep 17 00:00:00 2001 From: Yanhu007 Date: Wed, 15 Apr 2026 06:09:49 +0800 Subject: [PATCH] fix: parse leading-zero strings as decimal instead of invalid octal MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit cast.ToInt("08") returned 0 because strconv.ParseInt with base 0 treats leading zeros as octal, and 8 is not a valid octal digit. Now parseInt/parseUint try base 10 first, falling back to base 0 (auto-detect) for hex/octal/binary prefixed strings. This ensures: - "08", "09" → 8, 9 (previously 0) - "010" → 10 (previously 8, now decimal as users expect) - "0xff" → 255 (still works via fallback) - "0b1010" → 10 (still works via fallback) Fixes #290 --- number.go | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/number.go b/number.go index a58dc4d..71b3abe 100644 --- a/number.go +++ b/number.go @@ -405,18 +405,32 @@ func parseNumber[T Number](s string) (T, error) { } func parseInt[T integer](s string) (T, error) { - v, err := strconv.ParseInt(trimDecimal(s), 0, 0) + s = trimDecimal(s) + // Try base-10 first so that leading-zero strings like "08" parse as + // decimal 8 instead of being rejected as invalid octal. + v, err := strconv.ParseInt(s, 10, 0) if err != nil { - return 0, err + // Fall back to base-0 (auto-detect) to support "0x", "0o", "0b" prefixes. + v, err = strconv.ParseInt(s, 0, 0) + if err != nil { + return 0, err + } } return T(v), nil } func parseUint[T unsigned](s string) (T, error) { - v, err := strconv.ParseUint(strings.TrimLeft(trimDecimal(s), "+"), 0, 0) + s = strings.TrimLeft(trimDecimal(s), "+") + // Try base-10 first so that leading-zero strings like "08" parse as + // decimal 8 instead of being rejected as invalid octal. + v, err := strconv.ParseUint(s, 10, 0) if err != nil { - return 0, err + // Fall back to base-0 (auto-detect) to support "0x", "0o", "0b" prefixes. + v, err = strconv.ParseUint(s, 0, 0) + if err != nil { + return 0, err + } } return T(v), nil