Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix InexactError issue #102 #69

Merged
merged 1 commit into from
Feb 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading