From: Brendan Hansen Date: Wed, 28 Sep 2022 16:47:56 +0000 (-0500) Subject: float printing bugfix; added is_nan and is_inf X-Git-Url: https://git.brendanfh.com/?a=commitdiff_plain;h=d757711629e573d811145e9b3276840c91ab5b66;p=onyx.git float printing bugfix; added is_nan and is_inf --- diff --git a/core/conv.onyx b/core/conv.onyx index 11de869d..8a8d0c01 100644 --- a/core/conv.onyx +++ b/core/conv.onyx @@ -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; diff --git a/core/math.onyx b/core/math.onyx index 4460b573..6ce789ab 100644 --- a/core/math.onyx +++ b/core/math.onyx @@ -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; +} + //