Skip to content

Commit

Permalink
Make Float#to_s ignore NaN sign bit (#12399)
Browse files Browse the repository at this point in the history
* Make `Float#to_s` ignore NaN sign bit

* fixup
  • Loading branch information
HertzDevil authored Aug 18, 2022
1 parent d48b9f3 commit 2807146
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 8 deletions.
4 changes: 2 additions & 2 deletions spec/std/float_printer_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ describe "#print Float64" do
it { test_str "Infinity" }

it { test_pair 0x7ff8000000000000_u64, "NaN" }
it { test_pair 0xfff8000000000000_u64, "-NaN" }
it { test_pair 0xfff8000000000000_u64, "NaN" }

it { test_str "0.01" }
it { test_str "0.1" }
Expand Down Expand Up @@ -127,7 +127,7 @@ describe "#print Float32" do
it { test_pair Float32::INFINITY, "Infinity" }
it { test_pair -Float32::INFINITY, "-Infinity" }
it { test_pair 0x7fc00000_u32, "NaN" }
it { test_pair 0xffc80000_u32, "-NaN" }
it { test_pair 0xffc80000_u32, "NaN" }
it { test_pair 0.000001_f32, "1.0e-6" }
it { test_pair -0.0001_f32, "-0.0001" }
it { test_pair -0.00001_f32, "-1.0e-5" }
Expand Down
13 changes: 7 additions & 6 deletions src/float/printer.cr
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,20 @@ module Float::Printer
def print(v : Float64 | Float32, io : IO, *, point_range = -3..15) : Nil
d = IEEE.to_uint(v)

if IEEE.nan?(d)
io << "NaN"
return
end

if IEEE.sign(d) < 0
io << '-'
v = -v
end

if v == 0.0
io << "0.0"
elsif IEEE.special?(d)
if IEEE.inf?(d)
io << "Infinity"
else
io << "NaN"
end
elsif IEEE.inf?(d)
io << "Infinity"
else
internal(v, io, point_range)
end
Expand Down

0 comments on commit 2807146

Please sign in to comment.