33

Using the following code snippet:

(fromIntegral 100)/10.00

Using the Haskell '98 standard prelude, how do I represent the result with two decimals?

Thanks.

Marat Salikhov
  • 6,367
  • 4
  • 32
  • 35
Anders
  • 856
  • 1
  • 7
  • 14

2 Answers2

57

Just for the record:

import Numeric 
formatFloatN floatNum numOfDecimals = showFFloat (Just numOfDecimals) floatNum ""
Marat Salikhov
  • 6,367
  • 4
  • 32
  • 35
27

You can use printf :: PrintfType r => String -> r from Text.Printf:

Prelude> import Text.Printf
Prelude Text.Printf> printf "%.2f\n" (100 :: Float)
100.00
Prelude Text.Printf> printf "%.2f\n" $ fromIntegral 100 / 10.00
10.00

%f formats the second argument as a floating point number. %.2f indicates that only two digits behind the decimal point should be printed. \n represents a newline. It is not strictly necessary for this example.

Note that this function returns a value of type String or IO a, depending on context. Demonstration:

Prelude Text.Printf> printf "%.2f" (1337 :: Float) ++ " is a number"
"1337.00 is a number"

In this case printf returns the string "1337.00", because the result is passed as an argument to (++), which is a function that expects list arguments (note that String is the same as [Char]). As such, printf also behaves as sprintf would in other languages. Of course a trick such as appending a second string is not necessary. You can just explicitly specify the type:

Prelude Text.Printf> printf "%.2f\n" (1337 :: Float) :: IO a  
1337.00
Prelude Text.Printf> printf "%.2f\n" (1337 :: Float) :: String
"1337.00\n"
Stephan202
  • 59,965
  • 13
  • 127
  • 133
  • 2
    I'll rephrase the question :-) I want to return a string representation of a float with exactly two decimans - not print it to stdout. I can't find anything concrete on a 'sprintf' function in Haskell like I'd hoped. Any hints? – Anders Oct 13 '09 at 11:25
  • Try rounding then printing the float? – Jared Updike Nov 23 '09 at 19:50