Ona
Ona

Reputation: 7

Haskell: Converting Float to Int (mean average)

I have a function which must return an Int, however I need to use a local definition to find the average of three parameters; such that:

avg = (a + b + c) / 3

However this of course returns a float, how do I convert the result into an int (or more specifically round it up or down)?

Upvotes: 0

Views: 1699

Answers (1)

Random Dev
Random Dev

Reputation: 52280

as I commented you can use either round, ceiling or floor like this:

avg :: Integral a => a -> a -> a -> Int
avg a b c = round $ fromIntegral (a+b+c) / 3

or you can use div instead (which will truncate towards negative infinity ...):

avg' :: Integral a => a -> a -> a -> a
avg' a b c = (a+b+c) `div` 3

if you want different input types than you might have to use some other conversions too but I cannot tell from your question.

Upvotes: 2

Related Questions