# Passing a format string as a function argument

**URL:** <https://discourse.julialang.org/t/passing-a-format-string-as-a-function-argument/116929>\
**Category:** General Usage\
**Tags:** question\
**Created:** [July 11, 2024, 10:32pm UTC](https://discourse.julialang.org/t/passing-a-format-string-as-a-function-argument/116929 "2024-07-11T22:32:34Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![brombo](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/brombo/32/47867_2.png) [@brombo](https://discourse.julialang.org/u/brombo)\
**Post date:** [July 11, 2024, 10:32pm UTC](https://discourse.julialang.org/t/passing-a-format-string-as-a-function-argument/116929/1 "2024-07-11T22:32:34Z")

</div>

I am trying to pass a format string as a function argument in the following code -

```julia
using Printf

fmt = "%.0e"

function latex_exp_note(flt,fmt)
    s = @sprintf(fmt,flt)
    b,e = split(s,"e")
    e = replace(e,"+"=>"")
    e = replace(e,"0"=>"")
    s = raw"$"*b*raw"\times 10^{"*e*raw"}$"
    s = replace(s,"{}"=>"{0}")
    return latexstring(s)
end

display(latex_exp_note(2.5,fmt))

```

when I run the code I get this error -

LoadError: ArgumentError: First argument to `@sprintf` must be a format string.

how do it define `fmt` to be a format string that can be passed into a function?

---

<div class="post-metadata">

**Author:** ![bertschi](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bertschi/32/33462_2.png) [@bertschi](https://discourse.julialang.org/u/bertschi)\
**Post date:** [July 11, 2024, 10:54pm UTC](https://discourse.julialang.org/t/passing-a-format-string-as-a-function-argument/116929/2 "2024-07-11T22:54:36Z")

</div>

Short answer, you can’t pass it as an argument to the `@sprintf` macro.  
Instead use the function the macro call expands to:

```julia
s = Printf.format(fmt, fld)

```

and also the format string is not a string, but needs to be preprocessed via

```julia
fmt = Printf.format"%.0e"

```

See this [thread](https://discourse.julialang.org/t/printf-with-variable-format-string/3805) for the discussion of basically the same problem.

---

<div class="post-metadata">

**Author:** ![brombo](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/brombo/32/47867_2.png) [@brombo](https://discourse.julialang.org/u/brombo)\
**Post date:** [July 11, 2024, 11:44pm UTC](https://discourse.julialang.org/t/passing-a-format-string-as-a-function-argument/116929/3 "2024-07-11T23:44:41Z")

</div>

Thank you for a solution that worked. There needs to be more documentation on this subject.
