I want to display some Rational
values in their decimal expansion. That is, instead of displaying 3 % 4
, I would rather display 0.75
. I'd like this function to be of type Int -> Rational -> String
. The first Int
is to specify the maximum number of decimal places, since Rational
expansions may be non-terminating.
Hoogle and the haddocks for Data.Ratio didn't help me. Where can I find this function?
Arbitrary precision version that re-uses library code:
I know I've seen a function before that converts rationals into digits in a way that's easier to inspect (i.e. that makes it quite clear where the digits start repeating), but I can't seem to find it now. In any case, it's not hard to write, if that turns out to be a need; you just code up the usual long-division algorithm and watch for divisions you've already done.
Here is an arbitrary precision solution that doesn't use floats:
Here's one that I wrote a few weeks ago. You can specify the number of decimals you want (correctly rounded), or just pass
Nothing
in which case it will print the full precision, including marking the repeated decimals.You can make it. Not elegant, but does the job: