How to convert Int to Float and vice versa in Haskell
Overview
We might need to convert from one data type to another data type while writing code. Most programming languages provide a way to convert data types explicitly using methods or functions.
Convert Float to Int
In Haskell, we can convert Float to Int using the function round.
Syntax
Let's view the syntax of the function.
round float_value
Round syntax
Parameter
The round function takes the floating-point value as a parameter.
Return value
It returns an integer value.
Let's look at an example of this.
Code example
main::IO()main = dolet num = 555.0009 :: Float--convert float to intprint(round num)
Code explanation
- Line 4: We declare and initialize the float variable
num. - Line 6: We get the integer value from the floating-point value using the
roundfunction, and display it.
Convert Int to Float
In Haskell, we can convert Int to Float using the function fromIntegral.
Syntax
Let's view the syntax of the function.
fromIntegral integer
The syntax for fromIntegral
Parameter
The fromIntegral function takes an integer as a parameter.
Return value
It returns a floating-point value.
Let's take a look at an example of this.
Code example
main::IO()main = dolet num = 99999 :: Int--convert int to floatlet new_num = fromIntegral num :: Floatprint(new_num)
Code explanation
- Line 4: We declare and initialize the integer
num. - Line 6: We convert
inttofloatusing the functionfromIntegraland store the returned float value in the variablenew_num. - Line 7: We display the float value stored in the variable
new_num.