Skip to content

Commit

Permalink
fix remove_tail_zeros bug
Browse files Browse the repository at this point in the history
  • Loading branch information
kbkpbot committed Oct 6, 2024
1 parent 209c30f commit 664b2fd
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
6 changes: 5 additions & 1 deletion vlib/strconv/format_mem.c.v
Original file line number Diff line number Diff line change
Expand Up @@ -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++
}
Expand Down
7 changes: 7 additions & 0 deletions vlib/strconv/format_test.v
Original file line number Diff line number Diff line change
Expand Up @@ -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'
}

0 comments on commit 664b2fd

Please sign in to comment.