Printf with custom format (custom data type)

Hi all,

Is it possible to add format specifiers to printf for custom data types?

Thanks

Could this work for you:

using Printf

struct MyType; a::Float64; end

Base.show(io::IO, M::MyType) = @printf(io, "%.2f", M.a)

x = MyType(1.1)

or maybe this is better suited:

using Printf

struct MyType2; a::Float64; ϵ::Float64; end

myfmt = Printf.Format("%.3f +- %.3f")
Printf.format(M::MyType2) = Printf.format.(Ref(myfmt), M.a, M.ϵ)

M = MyType2(1.0, 0.2)
Printf.format(M)

"1.000 +- 0.200"

In general, no - custom format specifiers in format strings are not supported. I’d recommend the show approach insted.