I am writing a function in which I need to read a string contains floating point number and turn it back to Rational. But When I do toRational (read input :: Double), it will not turn for eg: 0.9 into 9 % 10 as expected, but instead 81….. % 9007…
Thx
I am writing a function in which I need to read a string contains
Share
This is correct behavior. The number
0.9is not representable as aDouble, not in Haskell, C, or Java. This is becauseDoubleandFloatuse base 2: they can only represent a certain subset of the dyadic fractions exactly.To get the behavior you want, import the
Numericmodule and use thereadFloatfunction. The interface is fairly wonky (it uses theReadStype), so you’ll have to wrap it a little. Here’s how you can use it:And, the result: