From 664b2fdff51eab65640e94b0c44e9e70f67ca786 Mon Sep 17 00:00:00 2001 From: kbkpbot Date: Sun, 6 Oct 2024 17:29:56 +0800 Subject: [PATCH] fix remove_tail_zeros bug --- vlib/strconv/format_mem.c.v | 6 +++++- vlib/strconv/format_test.v | 7 +++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/vlib/strconv/format_mem.c.v b/vlib/strconv/format_mem.c.v index fc5c2f6c3023ea..1b5dca4200aa1f 100644 --- a/vlib/strconv/format_mem.c.v +++ b/vlib/strconv/format_mem.c.v @@ -491,13 +491,17 @@ pub fn remove_tail_zeros(s string) string { if i_s < s.len && s[i_s] == `.` { mut i_s1 := i_s + 1 mut sum := 0 + mut i_s2 := i_s1 // last non-zero index after `.` for i_s1 < s.len && s[i_s1] >= `0` && s[i_s1] <= `9` { sum += s[i_s1] - u8(`0`) + if s[i_s1] != `0` { + i_s2 = i_s1 + } i_s1++ } // decimal part must be copied if sum > 0 { - for c_i in i_s .. i_s1 { + for c_i in i_s .. i_s2 + 1 { buf[i_d] = s[c_i] i_d++ } diff --git a/vlib/strconv/format_test.v b/vlib/strconv/format_test.v index 9a815981b7ac35..ffd469a90ab38f 100644 --- a/vlib/strconv/format_test.v +++ b/vlib/strconv/format_test.v @@ -119,3 +119,10 @@ fn test_sprintf_with_escape() { s := unsafe { strconv.v_sprintf('%d is 100%% awesome', n) } assert s == '69 is 100% awesome' } + +fn test_remove_tail_zeros() { + assert strconv.remove_tail_zeros('1.234000000000') == '1.234' + assert strconv.remove_tail_zeros('1.0000000') == '1' + assert strconv.remove_tail_zeros('1234') == '1234' + assert strconv.remove_tail_zeros('1.00000000007') == '1.00000000007' +}