How to format float numbers in human-friendly format?

I am writing a short script in Julia, and I need to print a bunch of floating point numbers for the user. If I just print("my number: $f"), I get output like "my number: 2.99999999999" which is too noisy. I want a human-friendly format. A good approximation would be just using two digits after the point. Is there convenient way to do this? I can use round(f; digits = 2), but that’s a lot of typing. I am looking at something a-la {f:.2}.

Here’s the tiny script in question: config/t at 72a432ffd6bd56db13658d961de9abb740136cb4 · matklad/config · GitHub

I don’t know how “noisy” it is for you, but the command for versatile printing is printf, which by the way is a lot faster than before in Julia 1.6

In this case, the command would be:

@printf "my number: %.2f" f

Aha, printf indeed works better, thanks!

It’s a bummer that I can’t do both string interpolation and formatted output, but I can live with that.

I don’t exactly know what you mean by string interpolation, but there is also a way to print to a string in the very same page, sprintf.

There are ways to combine values and string pieces:

  • Using string interpolation: "elapsed: $(f)s"
  • Using sprintf: @sprintf "number: %.2fs" f

The first is more convenient, as you don’t have to match format string with n arguments. The second one allows formatting. Ideally, it should be possible to have both. In Python, for example, it is possible to write f"elapsed: {f:.2}s".

Oh, I get it. Nope, it seems there is no alternative for that (that I know of), but I guess it should be relatively easy to make such thing.

If want to retain interpolation but you don’t need as much control over how it is printed, you can always use IOContext property :compact = true (see examples in I/O and Network · The Julia Language)

The Formatting package is an option:

julia> using Formatting

julia> printx(x,N) = sprintf1("%10.$(N)f",x)
printx (generic function with 1 method)

julia> printx(π,3)
"     3.142"

julia> printx(π,6)
"  3.141593"


That issue in particular is relevant: Support python style f"{x:0.2}" · Issue #41 · JuliaIO/Formatting.jl · GitHub

It mentions the StringLiterals package which comes closer to what @matklad is looking for.

None of this has the simplicity of {f:.2}… Maybe there’s room for another package :slight_smile: (or a PR to Formattting.jl?)