# Compiled sprintf?

**URL:** <https://discourse.julialang.org/t/compiled-sprintf/10580>\
**Category:** General Usage\
**Tags:** formatting\
**Created:** [April 27, 2018, 4:18pm UTC](https://discourse.julialang.org/t/compiled-sprintf/10580 "2018-04-27T16:18:42Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![iwelch](https://avatars.discourse-cdn.com/v4/letter/i/8c91f0/32.png) [@iwelch](https://discourse.julialang.org/u/iwelch)\
**Post date:** [April 27, 2018, 4:18pm UTC](https://discourse.julialang.org/t/compiled-sprintf/10580/1 "2018-04-27T16:18:42Z")

</div>

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

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

```

short of writing everything in macro rather than in julia?

regards,

/iaw

---

<div class="post-metadata">

**Author:** ![jmkuhn](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jmkuhn/32/2090_2.png) [@jmkuhn](https://discourse.julialang.org/u/jmkuhn)\
**Post date:** [April 27, 2018, 5:07pm UTC](https://discourse.julialang.org/t/compiled-sprintf/10580/2 "2018-04-27T17:07:43Z")

</div>

You can do this using the [Formatting.jl](https://github.com/JuliaIO/Formatting.jl) package.

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

```

---

<div class="post-metadata">

**Author:** ![ScottPJones](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/scottpjones/32/146_2.png) [@ScottPJones](https://discourse.julialang.org/u/ScottPJones)\
**Post date:** [April 27, 2018, 7:50pm UTC](https://discourse.julialang.org/t/compiled-sprintf/10580/3 "2018-04-27T19:50:04Z")

</div>

You can also use [the Format.jl package](https://github.com/JuliaString/Format.jl) in [the JuliaString org](https://github.com/JuliaString).  
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](https://github.com/JuliaString/StringLiterals.jl), 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 😀

---

<div class="post-metadata">

**Author:** ![iwelch](https://avatars.discourse-cdn.com/v4/letter/i/8c91f0/32.png) [@iwelch](https://discourse.julialang.org/u/iwelch)\
**Post date:** [April 28, 2018, 3:09am UTC](https://discourse.julialang.org/t/compiled-sprintf/10580/4 "2018-04-28T03:09:57Z")

</div>

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

regards,

/iaw
