Home > Mobile >  How to use function argument in `@sprintf` in Julia?
How to use function argument in `@sprintf` in Julia?

Time:11-28

The following errors:

function num_to_string(x,format="%.1f")
    @sprintf format x
end

The error is:

LoadError: MethodError: no method matching Printf.Format(::Symbol)

I tried using the @sprintf(format,x) form, as well as interpolating(?) like @sprintf $format x

How can I use variables in the @sprintf format?

CodePudding user response:

@sprintf is a macro, and converts the format string into a processed Format object during macro-expansion itself. This is good for performance, but means that @sprintf is limited to literal strings as formats, not variables.

However, you can directly make the function call that @sprintf ultimately makes, and since that would be an ordinary function call (and not a macro invocation), you can use a variable as the format argument:

julia> function num_to_string(x,fmt="%.1f")
           Printf.format(Printf.Format(fmt), x)
       end
num_to_string (generic function with 2 methods)

julia> num_to_string(45)
"45.0"

julia> num_to_string(pi, "%.5f")
"3.14159"

  • Related