v / vlib / strconv
Raw file | 92 loc (81 sloc) | 1.8 KB | Latest commit hash 017ace6ea
1import strconv
2
3/**********************************************************************
4*
5* String to float Test
6*
7**********************************************************************/
8
9fn test_atof() {
10 //
11 // test set
12 //
13
14 // float64
15 src_num := [
16 f64(0.3),
17 -0.3,
18 0.004,
19 -0.004,
20 0.0,
21 -0.0,
22 31234567890123,
23 ]
24
25 // strings
26 src_num_str := [
27 '0.3',
28 '-0.3',
29 '0.004',
30 '-0.004',
31 '0.0',
32 '-0.0',
33 '31234567890123',
34 ]
35
36 // check conversion case 1 string <=> string
37 for c, x in src_num {
38 // slow atof
39 val := strconv.atof64(src_num_str[c]) or { panic(err) }
40 assert val.strlong() == x.strlong()
41
42 // quick atof
43 mut s1 := (strconv.atof_quick(src_num_str[c]).str())
44 mut s2 := (x.str())
45 delta := s1.f64() - s2.f64()
46 // println("$s1 $s2 $delta")
47 assert delta < f64(1e-16)
48
49 // test C.atof
50 n1 := x.strsci(18)
51 n2 := f64(C.atof(&char(src_num_str[c].str))).strsci(18)
52 // println("$n1 $n2")
53 assert n1 == n2
54 }
55
56 // check conversion case 2 string <==> f64
57 // we don't test atof_quick beacuse we already know the rounding error
58 for c, x in src_num_str {
59 b := src_num[c].strlong()
60 value := strconv.atof64(x) or { panic(err) }
61 a1 := value.strlong()
62 assert a1 == b
63 }
64
65 // special cases
66 mut f1 := f64(0.0)
67 mut ptr := unsafe { &u64(&f1) }
68 ptr = unsafe { &u64(&f1) }
69
70 // double_plus_zero
71 f1 = 0.0
72 assert *ptr == u64(0x0000000000000000)
73 // double_minus_zero
74 f1 = -0.0
75 assert *ptr == u64(0x8000000000000000)
76 println('DONE!')
77}
78
79fn test_atof_errors() {
80 if x := strconv.atof64('') {
81 eprintln('> x: ${x}')
82 assert false // strconv.atof64 should have failed
83 } else {
84 assert err.str() == 'expected a number found an empty string'
85 }
86 if x := strconv.atof64('####') {
87 eprintln('> x: ${x}')
88 assert false // strconv.atof64 should have failed
89 } else {
90 assert err.str() == 'not a number'
91 }
92}