Skip to content

Commit

Permalink
Fix InexactError issue #102
Browse files Browse the repository at this point in the history
  • Loading branch information
ScottPJones committed Feb 14, 2024
1 parent f068523 commit c52c864
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/fmtcore.jl
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,19 @@ function _pfmt_i(out::IO, fs::FormatSpec, x::Integer, op::Op) where {Op}
postpad == 0 || _repprint(out, fs.fill, postpad)
end

function _truncval(v)
try
return trunc(Integer, v)
catch e
e isa InexactError || rethrow(e)
end
try
return trunc(Int128, v)
catch e
e isa InexactError || rethrow(e)
end
trunc(BigInt, v)
end

### print floating point numbers

Expand All @@ -162,7 +175,7 @@ function _pfmt_f(out::IO, fs::FormatSpec, x::AbstractFloat)
prec = fs.prec
rax = round(abs(x); digits = prec)
sch = _signchar(x, fs.sign)
intv = trunc(Integer, rax)
intv = _truncval(rax)
decv = rax - intv

# calculate length
Expand Down
3 changes: 3 additions & 0 deletions test/fmtspec.jl
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,9 @@ end
# Floating point error can upset this one (i.e. 0.99500000 or 0.994999999)
@test (pyfmt(".2f", 0.995) == "1.00" || pyfmt(".2f", 0.995) == "0.99")
@test pyfmt(".2f", 0.994) == "0.99"

# issue #102 (from Formatting.jl)
@test pyfmt("15.6f", 1e20) == "100000000000000000000.000000"
end

@testset "Format floating point (e)" begin
Expand Down

0 comments on commit c52c864

Please sign in to comment.