开发者

How to return float number with 2 digits after decimal point?

I have some simple function

f :: Float -> Float开发者_StackOverflow社区
f x = x

Prelude> f 5.00
5.0

Why not 5.00? How can I achieve this?


If you want something from base then use showGFloat:

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


You can use printf

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


Since: 4.7.0.0, one can use showGFloatAlt:

This behaves as showFFloat, except that a decimal point is always guaranteed, even if not needed.

and the documentation for the old showGFloat doesn't say that a decimal point is always guaranteed.

(But I don't see any difference actually in my system:

$ 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"

I wonder why...)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜