float printing bugfix; added is_nan and is_inf
authorBrendan Hansen <brendan.f.hansen@gmail.com>
Wed, 28 Sep 2022 16:47:56 +0000 (11:47 -0500)
committerBrendan Hansen <brendan.f.hansen@gmail.com>
Wed, 28 Sep 2022 16:47:56 +0000 (11:47 -0500)
core/conv.onyx
core/math.onyx

index 11de869decdd0685a40bef664c56a98b0dd4d0f7..8a8d0c0182ff5a126869ff058b6f3ef7c1b06b8e 100644 (file)
@@ -281,7 +281,16 @@ u64_to_str :: (n: u64, base: u64, buf: [] u8, min_length := 0, prefix := false)
 // This is better than what used to be, but still relies on converting the integer
 // part of the float to an integer, which could overflow.
 f64_to_str :: (f: f64, buf: [] u8, digits_after_decimal := 4) -> str {
-    math :: package core.math
+    math :: package core.math;
+
+    if math.is_nan(f) {
+        return format(buf, "NaN");
+    }
+
+    if math.is_inf(f) {
+        if f > 0 do return format(buf, "Inf");
+        else     do return format(buf, "-Inf");
+    }
 
     len := 0;
 
index 4460b5739382652889a2b00cf27705951a3cc8f1..6ce789abe64da2df02f72d0117567bc26cc7237a 100644 (file)
@@ -340,6 +340,43 @@ lcm :: (a: $T, b: T) -> T {
     return (a * b) / gcd(a, b);
 }
 
+is_nan :: #match #local {}
+
+#overload
+is_nan :: (x: f32) -> bool {
+    v := x;
+    i := *cast(^u32) ^v;
+    return (i & 0x7f800000) == 0x7f800000
+        && (i & 0x007fffff) != 0;
+}
+
+#overload
+is_nan :: (x: f64) -> bool {
+    v := x;
+    i := *cast(^u64) ^v;
+    return (i & 0x7ff0000000000000) == 0x7ff0000000000000
+        && (i & 0x000fffffffffffff) != 0;
+}
+
+
+is_inf :: #match #local {}
+
+#overload
+is_inf :: (x: f32) -> bool {
+    v := x;
+    i := *cast(^u32) ^v;
+    return (i & 0x7f800000) == 0x7f800000
+        && (i & 0x007fffff) == 0;
+}
+
+#overload
+is_inf :: (x: f64) -> bool {
+    v := x;
+    i := *cast(^u64) ^v;
+    return (i & 0x7ff0000000000000) == 0x7ff0000000000000
+        && (i & 0x000fffffffffffff) == 0;
+}
+
 
 
 //