Skip to content

Commit 491d6f4

Browse files
authored
strconv: fix remove_tail_zeros bug (fix #22421) (#22422)
1 parent 6ed1765 commit 491d6f4

File tree

4 files changed

+18
-7
lines changed

4 files changed

+18
-7
lines changed

vlib/strconv/format_mem.c.v

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -491,13 +491,17 @@ pub fn remove_tail_zeros(s string) string {
491491
if i_s < s.len && s[i_s] == `.` {
492492
mut i_s1 := i_s + 1
493493
mut sum := 0
494+
mut i_s2 := i_s1 // last non-zero index after `.`
494495
for i_s1 < s.len && s[i_s1] >= `0` && s[i_s1] <= `9` {
495496
sum += s[i_s1] - u8(`0`)
497+
if s[i_s1] != `0` {
498+
i_s2 = i_s1
499+
}
496500
i_s1++
497501
}
498502
// decimal part must be copied
499503
if sum > 0 {
500-
for c_i in i_s .. i_s1 {
504+
for c_i in i_s .. i_s2 + 1 {
501505
buf[i_d] = s[c_i]
502506
i_d++
503507
}

vlib/strconv/format_test.v

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,3 +119,10 @@ fn test_sprintf_with_escape() {
119119
s := unsafe { strconv.v_sprintf('%d is 100%% awesome', n) }
120120
assert s == '69 is 100% awesome'
121121
}
122+
123+
fn test_remove_tail_zeros() {
124+
assert strconv.remove_tail_zeros('1.234000000000') == '1.234'
125+
assert strconv.remove_tail_zeros('1.0000000') == '1'
126+
assert strconv.remove_tail_zeros('1234') == '1234'
127+
assert strconv.remove_tail_zeros('1.00000000007') == '1.00000000007'
128+
}
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
fn test_string_interpolation_float_fmt() {
22
mut a := 76.295
33
eprintln('${a:8.2}')
4-
assert '${a:8.2}' == ' 76.30'
4+
assert '${a:8.2}' == ' 76.3'
55
eprintln('${a:8.2f}')
66
assert '${a:8.2f}' == ' 76.30'
77

88
a = 76.296
99
eprintln('${a:8.2}')
10-
assert '${a:8.2}' == ' 76.30'
10+
assert '${a:8.2}' == ' 76.3'
1111
eprintln('${a:8.2f}')
1212
assert '${a:8.2f}' == ' 76.30'
1313
}

vlib/v/tests/casts/cast_to_empty_interface_test.v

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@ fn test_cast_to_empty_interface() {
2222
assert ret_strings[1] == 'int 22'
2323
assert ret_strings[2] == 'int 8888'
2424
assert ret_strings[3] == 'int 9999'
25-
assert ret_strings[4] == 'f64 1.110'
26-
assert ret_strings[5] == 'f64 2.220'
27-
assert ret_strings[6] == 'f64 8.880'
28-
assert ret_strings[7] == 'f64 9.990'
25+
assert ret_strings[4] == 'f64 1.11'
26+
assert ret_strings[5] == 'f64 2.22'
27+
assert ret_strings[6] == 'f64 8.88'
28+
assert ret_strings[7] == 'f64 9.99'
2929
}

0 commit comments

Comments
 (0)