简单包含
Rational
在里面
printf
输出可以使用
%s
和
show
:
> printf "... %s ...\n" (show $ 123 % 456)
... 41 % 152 ...
但是,能够使用
%f
格式代码:
> printf "... %.30f ...\n" (123 % 456)
... 0.269736842105263157894736842105 ...
请注意,通过转换到
Double
(如使用
fromRational
)不允许我所寻找的任意精度:
> printf "... %.30f ...\n" (fromRational $ 123 % 456)
... 0.269736842105263160000000000000 ...
这个
%v
代码可用于生成与
显示
,可能还允许使用一些修饰符。
是否有任何原因不应该使用自定义格式化程序(的实例
PrintfArg (Ratio a)
)?
作为参考,这里有一个独立的函数,我正在使用它作为部分解决方案:
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 ...
但是,这不允许使用修饰符,并且需要在不同的位置指定宽度。