strconv: fix remove_tail_zeros bug (fix #22421) (#22422)

This commit is contained in:
kbkpbot 2024-10-06 21:48:08 +08:00 committed by GitHub
parent 6ed176515d
commit 491d6f4955
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 18 additions and 7 deletions

View File

@ -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++
}

View File

@ -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'
}

View File

@ -1,13 +1,13 @@
fn test_string_interpolation_float_fmt() {
mut a := 76.295
eprintln('${a:8.2}')
assert '${a:8.2}' == ' 76.30'
assert '${a:8.2}' == ' 76.3'
eprintln('${a:8.2f}')
assert '${a:8.2f}' == ' 76.30'
a = 76.296
eprintln('${a:8.2}')
assert '${a:8.2}' == ' 76.30'
assert '${a:8.2}' == ' 76.3'
eprintln('${a:8.2f}')
assert '${a:8.2f}' == ' 76.30'
}

View File

@ -22,8 +22,8 @@ fn test_cast_to_empty_interface() {
assert ret_strings[1] == 'int 22'
assert ret_strings[2] == 'int 8888'
assert ret_strings[3] == 'int 9999'
assert ret_strings[4] == 'f64 1.110'
assert ret_strings[5] == 'f64 2.220'
assert ret_strings[6] == 'f64 8.880'
assert ret_strings[7] == 'f64 9.990'
assert ret_strings[4] == 'f64 1.11'
assert ret_strings[5] == 'f64 2.22'
assert ret_strings[6] == 'f64 8.88'
assert ret_strings[7] == 'f64 9.99'
}