【问题标题】:How to return float number with 2 digits after decimal point?如何返回小数点后两位的浮点数?
【发布时间】:2011-11-18 02:57:40
【问题描述】:

我有一些简单的功能

f :: Float -> Float
f x = x

Prelude> f 5.00
5.0

为什么不5.00?我怎样才能做到这一点?

【问题讨论】:

  • 你真正想要达到什么目的。看着你的任务,你好像不懂浮点数。

标签: haskell floating-point formatting printf pretty-print


【解决方案1】:

由于:4.7.0.0,可以使用showGFloatAlt

这与 showFFloat 的行为相同,但始终保证小数点,即使不需要。

旧的showGFloat 的文档并没有说总是保证小数点。

(但我实际上在我的系统中没有看到任何区别:

$ ghci
GHCi, version 8.6.4: http://www.haskell.org/ghc/  :? for help
Prelude> import Numeric
Prelude Numeric> showGFloat (Just 2) 5.0 ""
"5.00"
Prelude Numeric> showGFloatAlt (Just 2) 5.0 ""
"5.00"
Prelude Numeric> showGFloat Nothing 5.0 ""
"5.0"
Prelude Numeric> showGFloatAlt Nothing 5.0 ""
"5.0"

我想知道为什么...)

【讨论】:

    【解决方案2】:

    如果您想要来自base 的东西,请使用showGFloat

     > import Numeric
     > showGFloat (Just 2) 1.99438 ""
     "1.99"
     > :t showGFloat
     showGFloat :: RealFloat a => Maybe Int -> a -> ShowS
    

    【讨论】:

      【解决方案3】:

      您可以使用printf

      printf "%.2f" (f :: Float)
      

      【讨论】:

      • 上面的代码抛出了一些错误(Couldn't match expected type Float with actual type Float -> Float)。所以我用了这个:line n = printf "%.2f\n" $ f n.
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-18
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      相关资源
      最近更新 更多