如何在 Julia 中使用 `@sprintf` 中的函数参数?

Ale*_*lec 6 string format macros julia

出现以下错误:

function num_to_string(x,format="%.1f")
    @sprintf format x
end
Run Code Online (Sandbox Code Playgroud)

错误是:

LoadError: MethodError: no method matching Printf.Format(::Symbol)
Run Code Online (Sandbox Code Playgroud)

我尝试使用@sprintf(format,x)表格,以及插值(?)像@sprintf $format x

如何使用@sprintf格式中的变量?

sun*_*ica 8

@sprintfFormat是一个宏,并在宏扩展本身期间将格式字符串转换为已处理的对象。这对性能有好处,但意味着@sprintf仅限于文字字符串作为格式,而不是变量。

@sprintf 但是,您可以直接进行最终生成 的函数调用,并且由于这将是普通函数调用(而不是宏调用),因此您可以使用变量作为格式参数:

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"

Run Code Online (Sandbox Code Playgroud)