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.
In Haskell, we can convert Int to Float using the function fromIntegral .
The atof() function converts a character string to a double-precision floating-point value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type.
To convert an integer data type to float you can wrap the integer with float64() or float32. Explanation: Firstly we declare a variable x of type int64 with a value of 5. Then we wrap x with float64(), which converts the integer 5 to float value of 5.00.
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.
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
did you try:
intToFloat :: Int -> Float
intToFloat n = fromInteger (toInteger n)
Additionally see here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With