Simple question here, how could I emulate the effect of string(Int, pad=n)
with floats?
Using string
itself throws an error.
You can use the Printf
standard library:
julia> using Printf
julia> @sprintf("%10.4g", 3.14159) # 10 characters, 4 digits of precision, right-justified
" 3.142"
julia> @sprintf("%-10.4g", 3.14159) # 10 characters, 4 digits of precision, left-justified
"3.142 "
julia> Printf.format(Printf.format"%-10.4g", 3.14159) # equivalent to the previous
"3.142 "
See printf, fprintf, sprintf, snprintf, printf_s, fprintf_s, sprintf_s, snprintf_s - cppreference.com for more options. You can also use this library to get finer control of integer printing.
2 Likes
An alternative, fwiw:
julia> lpad(string(round(pi, digits=2)), 6)
" 3.14"
julia> lpad(string(round(pi, digits=2)), 6, '0')
"003.14"