Haskell int to float and char to float

10,830

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)

Additionally see here

Share:
10,830
Jake
Author by

Jake

Updated on June 26, 2022

Comments

  • Jake
    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
    sepp2k almost 13 years
    You can just do char2float n = read [n]. No need for fromInteger.
  • John L
    John L almost 13 years
    I knew there was a function like digitToInt, but I was too lazy to look for it. Thanks!