Sajid Anower
Sajid Anower

Reputation: 171

How to convert from Float to Int in Haskell

I wrote a function in Haskell

toInt :: Float -> Int
toInt x = round $fromIntegral x

It is supposed to take in an Float and return the equivalent Int. I come from a C programming background, and in C, we could just cast it as an int.

However, in this case, I get the following compile error

No instance for (Integral Float)
arising from a use of `fromIntegral'
In the second argument of `($)', namely `fromIntegral x'
In the expression: round $ fromIntegral x
In an equation for `toInt': toInt x = round $ fromIntegral x

Any idea on how to fix this?

Upvotes: 16

Views: 34596

Answers (1)

Chad Gilbert
Chad Gilbert

Reputation: 36385

Your type annotation specifies that x should be a Float, which means it can't be a parameter to fromIntegral since that function takes an Integral.

You could instead just pass x to round:

toInt :: Float -> Int
toInt x = round x

which in turn can be slimmed down to:

toInt :: Float -> Int
toInt = round

which implies that you may be better off just using round to begin with, unless you have some specialized way of rounding.

Upvotes: 22

Related Questions