DEV Community

Discussion on: Daily Challenge #49 - Dollars and Cents

Collapse
 
aminnairi profile image
Amin

My take at the challenge written in Haskell.

toFloat :: String -> Float
toFloat string = read string :: Float

decimalToInt :: Float -> Int
decimalToInt float =
  round
    $ (*) 100
    $ toFloat
    $ take 5
    $ show
    $ float - (fromIntegral $ floor float)

decimalToDollar :: Float -> String
decimalToDollar float =
  "$" 
    ++ (show $ round float)
    ++ "."
    ++ (show $ decimalToInt float)

main :: IO ()
main = do
  putStrLn $ show $ decimalToDollar 6.2 -- "$6.20"
  putStrLn $ show $ decimalToDollar 6.227 -- "$6.23"

Try it online.

For some reason, I get imprecise floating point numbers when grabbing the decimal part of a floating point number in Haskell. I'm pretty new to this language so I must miss something. Feel free to improve my work here.