If I make a function return a custom type so that I can create a formatted show method for it, what functions do I then need to extend to make my type behave like Float64 everywhere? I don’t see anything like that listed in Interfaces · The Julia Language.
using Format
struct PercentError
x::Float64
end
Base.show(io::IO, x::PercentError) = print(io, format(x.x, commas=true, precision=3, suffix=" %"))
This is definitely an X-Y problem because defining your own number type is almost certainly overkill for whatever printing problem you face. You can see the implementation of Dual Numbers as an example, but in general implementing your own number type just to print things easier is a lot.
It really seems like a PercentError storing a Float64 that way shouldn’t be treated like one. Scaling by other Real numbers could reasonably result in another PercentError. However, scaling by another PercentError is a problem: 1% stores 1.0, but 1%^2 is 0.01%, which stores 0.01, not 1.0^2 == 1.0.
Yeah, I thought this may be a potential solution for the printing issue in the linked thread. I guess not. I want to remind myself that my function output already multiplied by 100 to convert to percent. I could print the answer formatted at the end of the function, but it will still return the raw answer right below that unless I remember to suppress with ;.