Simple inclusion of a Rational
in printf
output can be accomplished using %s
and show
:
> printf "... %s ...\n" (show $ 123 % 456)
... 41 % 152 ...
However, it would be useful to be able to use the %f
format code as well:
> printf "... %.30f ...\n" (123 % 456)
... 0.269736842105263157894736842105 ...
Note that formatting via a conversion to Double
(eg using fromRational
) would not allow the arbitrary precision I'm looking for:
> printf "... %.30f ...\n" (fromRational $ 123 % 456)
... 0.269736842105263160000000000000 ...
The %v
code could be used to produce the same output as show
, and perhaps some modifiers could be allowed with it.
Is there any reason why this shouldn't be accomplished with a custom formatter (an instance of PrintfArg (Ratio a)
)?
For reference, here's a standalone function that I'm using as a partial workaround:
showDecimal :: RealFrac a => Int -> a -> String
showDecimal n r = printf "%d.%0*d" (i :: Integer) n (abs d :: Integer)
where (i, d) = (round $ r * 10^n) `quotRem` (10^n)
> printf "... %35s ...\n" (showDecimal 30 $ 123 % 456)
... 0.269736842105263157894736842105 ...
However, this doesn't allow the use of modifiers, and involves specifying widths in separate places.