Haskell int to float and char to float
Solution 1
Questions like this can be answered with hoogle.
For example, Hoogle for "Char -> Int" and the first function listed will do it (ord
, mentioned in other answers, is the second result):
digitToInt :: Char -> Int
Though your need for a function :: Char -> Float does mandate using read
(third result down) or a combination of digitToInt and a function :: Int -> Float:
digitToFloat = toEnum . digitToInt
Solution 2
fromIntegral
will convert from Int to Float.
For Char to Float, it depends. If you want to get the ASCII value of a Char (ignoring Unicode for now), use Data.Char.ord:
Prelude Data.Char> fromIntegral (ord '2') :: Float
50.0
If you want to read the digit of a Char, i.e. '2'
becomes the value 2
, you can do this:
char2float :: Char -> Float
char2float n = fromInteger (read [n])
Prelude Data.Char> char2float '2'
2.0
If you're going to do a lot of this, you might consider using an actual parsing library to get actual error handling.
Solution 3
did you try:
intToFloat :: Int -> Float
intToFloat n = fromInteger (toInteger n)
Jake
Updated on June 26, 2022Comments
-
Jake over 1 year
Is there a function in haskell which converts from int to float, and from char to float?
I know that there is a function that converts from char to int and int to char.
-
sepp2k almost 13 yearsYou can just do
char2float n = read [n]
. No need forfromInteger
. -
John L almost 13 yearsI knew there was a function like digitToInt, but I was too lazy to look for it. Thanks!