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.
Float
to Int
In Haskell, we can convert Float
to Int
using the function round
.
Let's view the syntax of the function.
round float_value
The round
function takes the floating-point value as a parameter.
It returns an integer value.
Let's look at an example of this.
main::IO()main = dolet num = 555.0009 :: Float--convert float to intprint(round num)
num
.round
function, and display it.Int
to Float
In Haskell, we can convert Int
to Float
using the function fromIntegral
.
Let's view the syntax of the function.
fromIntegral integer
The fromIntegral
function takes an integer as a parameter.
It returns a floating-point value.
Let's take a look at an example of this.
main::IO()main = dolet num = 99999 :: Int--convert int to floatlet new_num = fromIntegral num :: Floatprint(new_num)
num
.int
to float
using the function fromIntegral
and store the returned float value in the variable new_num
.new_num
.