Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell int to float and char to float

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.

like image 500
Jake Avatar asked Nov 09 '10 17:11

Jake


People also ask

How do I convert Int to float Haskell?

In Haskell, we can convert Int to Float using the function fromIntegral .

Can char convert to float?

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.

Can Int be converted to float?

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.


3 Answers

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.

like image 101
John L Avatar answered Sep 21 '22 12:09

John L


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
like image 35
Thomas M. DuBuisson Avatar answered Sep 22 '22 12:09

Thomas M. DuBuisson


did you try:

intToFloat :: Int -> Float
intToFloat n = fromInteger (toInteger n)

Additionally see here

like image 28
codymanix Avatar answered Sep 21 '22 12:09

codymanix