📅  最后修改于: 2023-12-03 15:01:06.860000             🧑  作者: Mango
In Haskell, there are two main ways to convert a floating point number to an integer: using the floor
or ceiling
functions or using the round
function. Here is an overview of these functions:
floor
and ceiling
The floor
function takes a floating point number and rounds it down to the next integer, while the ceiling
function rounds it up to the next integer. For example:
floor 3.7 -- returns 3
ceiling 3.7 -- returns 4
floor (-3.7) -- returns -4
ceiling (-3.7) -- returns -3
Note that the functions return an Integral
type, which can be converted to an Int
type using the fromIntegral
function:
let x = floor 3.7 :: Int
let y = ceiling 3.7 :: Int
let z = floor (-3.7) :: Int
let w = ceiling (-3.7) :: Int
round
The round
function rounds a floating point number to the nearest integer. If the number is exactly halfway between two integers, it rounds to the even integer. For example:
round 3.2 -- returns 3
round 3.7 -- returns 4
round (-3.2) -- returns -3
round (-3.7) -- returns -4
Again, note that the function returns an Integral
type, which can be converted to an Int
type using the fromIntegral
function:
let x = round 3.2 :: Int
let y = round 3.7 :: Int
let z = round (-3.2) :: Int
let w = round (-3.7) :: Int
In Haskell, converting a floating point number to an integer is easy thanks to the floor
, ceiling
, and round
functions. Remember to use the fromIntegral
function when you need to convert the result to an Int
type.