I'm practicing Haskell by writing a program that will convert a price in cents into dollars. Obviously, this means that my Int will need to become a Double, but I want my final output to be that of a String. My code:
First, I defined my
type Price = Int
Then, I wrote my module:
formatDollars :: Price -> String formatDollars x = show (fromIntegral (x `div` 100))
My test input for
x was 188, which should give me 1.88.
But my output is always
"1". This makes me think that my fromIntegral function might not be utilized correctly in my code, as if it's truncating after the decimal. Since I'm so new to Haskell, I'm sure it's a simple mistake; could someone help me out?
188 `div` 100 == 1
You want to convert to
Double before doing the division. (And then do real division, not integer division.)
formatDollars x = show ((fromIntegral x) / 100)