本文介绍了如何将Rational转换为"pretty"细绳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想以小数位数显示一些Rational
值.即,我宁愿显示0.75
,也不显示3 % 4
.我希望此函数的类型为Int -> Rational -> String
.第一个Int
用于指定最大小数位数,因为Rational
扩展名可能是无终止的.
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.
嘘而针对Data.Ratio的黑线没有帮帮我.在哪里可以找到此功能?
Hoogle and the haddocks for Data.Ratio didn't help me. Where can I find this function?
推荐答案
这是不使用浮点数的任意精度解决方案:
Here is an arbitrary precision solution that doesn't use floats:
import Data.Ratio
display :: Int -> Rational -> String
display len rat = (if num < 0 then "-" else "") ++ (shows d ("." ++ take len (go next)))
where
(d, next) = abs num `quotRem` den
num = numerator rat
den = denominator rat
go 0 = ""
go x = let (d, next) = (10 * x) `quotRem` den
in shows d (go next)
这篇关于如何将Rational转换为"pretty"细绳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!