How to print a number to X digits?

Hello!

Suppose I have the number, “1”, how would I make it so that it would always be printed as “1.000”?

Kind regards

julia> using Printf

julia> a = 1;

julia> @printf("%.3f\n", a)
1.000

There’s also @sprintf to get a string value, see https://docs.julialang.org/en/v1/stdlib/Printf/ for details.

3 Likes

You can set it for a whole REPL session instead of for every instance. For example, the following uses 4-digit MATLAB-like formatting:

julia> using Printf

julia> Base.show(io::IO, f::Float64) = @printf(io, "%.4f", f)

julia> 1.0
1.0000

julia> 2/3
0.6667

julia> rand(5)
5-element Array{Float64,1}:
 0.4112
 0.4889
 0.1706
 0.4589
 0.7526
3 Likes