Skip to content

Commit 5b585dc

Browse files
committed
test and fix float.str() precision
1 parent 962ab4a commit 5b585dc

4 files changed

Lines changed: 25 additions & 14 deletions

File tree

lib/builtin/number.c.bt

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -54,15 +54,15 @@ pub fun (n u64) str() string {
5454
}
5555

5656
pub fun (n f32) str() string {
57-
length := #C.snprintf(#C.'NULL' as &u8, 0, "%g".str, n as f64)
57+
length := #C.snprintf(#C.'NULL' as &u8, 0, "%.9g".str, n as f64)
5858
buf := #C.malloc(length + 1)
59-
_ = #C.snprintf(buf, length + 1, "%g".str, n as f64)
59+
_ = #C.snprintf(buf, length + 1, "%.9g".str, n as f64)
6060
return from_c_string(buf)
6161
}
6262

6363
pub fun (n f64) str() string {
64-
length := #C.snprintf(#C.'NULL' as &u8, 0, "%g".str, n)
64+
length := #C.snprintf(#C.'NULL' as &u8, 0, "%.17g".str, n)
6565
buf := #C.malloc(length + 1)
66-
_ = #C.snprintf(buf, length + 1, "%g".str, n)
66+
_ = #C.snprintf(buf, length + 1, "%.17g".str, n)
6767
return from_c_string(buf)
6868
}

tests/auto_str/auto_str_test.bt

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,16 @@ fun test_array() {
55
a := [true, false, true]
66
assert a.str() == "[true, false, true]"
77
}
8+
9+
struct Bar {
10+
f f64
11+
}
12+
13+
fun test_struct() {
14+
b := Bar {
15+
f = 3.14
16+
}
17+
assert b.str() == 'Bar{
18+
f = 3.14
19+
}'
20+
}

tests/auto_str/auto_str_test.js.bt

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ fun test_map() {
1010
assert m.str() == "{'foo': 62, 'bar': 31}"
1111
}
1212

13-
// TODO C floats
1413
struct Bar {
1514
f f64
1615
}
@@ -19,15 +18,7 @@ struct Foo {
1918
b Bar
2019
}
2120

22-
fun test_struct() {
23-
b := Bar {
24-
f = 3.14
25-
}
26-
assert b.str() == 'Bar{
27-
f = 3.14
28-
}'
29-
}
30-
21+
// TODO C fix nested structs
3122
fun test_nested_struct() {
3223
f := Foo {}
3324
assert f.str() == 'Foo{
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
// SPDX-FileCopyrightText: Lukas Neubert
2+
// SPDX-License-Identifier: MIT
3+
4+
fun test_float_str_precision() {
5+
f := 123.45678901234567890
6+
assert f.str() == '123.45678901234568'
7+
}

0 commit comments

Comments
 (0)