Compiled sprintf?

does julia have a non-macro sprintf? how would one write

f(x::AbstractFloat, fmt="%7.4f")= @sprintf(fmt, x)

short of writing everything in macro rather than in julia?

regards,

/iaw

You can do this using the Formatting.jl package.

using Formatting
f(x::AbstractFloat, fmt="%7.4f") = sprintf1(fmt, x)
f(3.55, "%12.3f")
1 Like

You can also use the Format.jl package in the JuliaString org.
It is based on the Formatting.jl package that @jmkuhn mentioned, but there are some enhancements from PRs that never got merged into Formatting.jl.
The API is slightly different, instead of sprintf1 it is cfmt, fmt is now pyfmt, and there is a new fmt which formats based on settable type specific defaults (which is very convenient)

You could also use the StringLiterals package, which allows you do use the formatting in string literals with interpolation, so instead of the above example, you’d have:
f"\%7.4f(x)" or f"\%12.3f(3.55)". IMO this is the most convenient way to do formatted output in Julia :grinning:

3 Likes

I just tried. StringLiterals looks cool, but it does not seem to be in the julia repository. :frowning:

regards,

/iaw