I want to be able to be able to truncate a float
or double
in a similar way you would in Java: (int)5.583
, for example.
I've done some research and, to my knowledge, there's nothing imported in Prelude for this. So I'm wondering how I would construct a function that does it. I thought maybe if I did show 5.583
and then took a substring up to the decimal point and then converted that to an Int
, but that seems like it would be terribly inefficient when using only recursion. So is there a more simple way to go about it?
I want to be able to be able to truncate
float
ordouble
Delightfully, the function that truncates fractionals to integrals is named "truncate".
https://www.stackage.org/haddock/lts-8.4/base-4.9.1.0/Prelude.html#v:truncate
λ> truncate 5.583
5
Its type is
truncate :: (Real a, Fractional a, Integral b) => a -> b
This is just an ordinary function. Haskell does not have any language feature (or kludge, if you will) akin to type casting in Java.
Converting floating point numbers with ghc is possible with:
λ> :m GHC.Float
λ> :t float2Double
float2Double :: Float -> Double
λ> :t double2Float
double2Float :: Double -> Float
λ> :t double2Int
double2Int :: Double -> Int
λ> :t float2Int
float2Int :: Float -> Int
λ> :t int2Double
int2Double :: Int -> Double
λ> :t int2Float
int2Float :: Int -> Float
But for floating point numbers to ints I'd recommend using ceiling
, round
and floor
, and fromIntegral
for backwads conversion.
Edit: after reading the question more carefully, @Chris Martin's answer is the correct one:
λ> :t truncate
truncate :: (Integral b, RealFrac a) => a -> b
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With