Error while formatting a specific number!

This seems total crazy to me:

so in the REPL I write:

julia> using Formatting
julia> ff= string(“{:.e”,4,“E”,“}”}
“{:.4e}”

Then I use ff to format a number like:
julia> zz = Formatting.format(ff,1E-8)
“1.0000e-08” # correct

and,
julia> zz = Formatting.format(ff,2E-8)
“2.0000e-08” # correct

BUT, for the specific number 3E-8

I get:
julia> zz = Formatting.format(ff,3.0E-8)
“2.10000E-08” # WRONG!!

BUT
julia> zz = Formatting.format(ff,3.0E-9)
“3.0000E-09” # correct

So please tell my that I’m doing something stupid and this is not a bug. Works the same way in a .jl script. Version 1.6.1 (2021-04-23)

zz = Formatting.format(ff,30.0E-9)
“2.10000E-08” # WRONG!!

Also gives the same erroneous result.

There seem to be some longstanding bugs in the floating-point formatting provided by the Formatting.jl package (e.g. printfmt("1:.4e, 40000.0) prints 3.10000e+04 · Issue #71 · JuliaIO/Formatting.jl · GitHub).

I would tend to recommend using Julia’s Printf standard library instead:

julia> using Printf

julia> @sprintf("%0.4E", 3.0e-8)
"3.0000E-08"

PS. Please quote your code.

2 Likes

Ok thanks. The reason I used Formatting.format is because I need the actual formatting string to be a variable since in my use case I am change the significant digits (e.g. might be “{:.5e}” vs. “{:.4e}” ) and @sprintf can’t handle a variable for the string. Guess I’'ll try a different approach.

This should be supported soon in Printf (adding dynamic width and precision to printf by johanmon · Pull Request #40105 · JuliaLang/julia · GitHub) but won’t be in an official release until Julia 1.8, unfortunately.

1 Like