Home > OS >  Haskell Float to Int to Float conversion Error
Haskell Float to Int to Float conversion Error

Time:11-14

I want to convert the a Floating Point Number (0,123456) and round it with b (positive whole number). I use the truncate function to round the Floating point number to a specific length "b"

This is the formula i came up with, however I get an error when compiling with the GHCI

The Function:

calcFloatingNum:: Double -> Int -> Int -> Float
calcFloatingNum a b = truncate ( a * 10^b) /10^b

The Error Code:

   * No instance for (Integral Double)
        arising from a use of `truncate'
    * In the first argument of `(/)', namely `truncate (a * 10 ^ b)'
      In the expression: truncate (a * 10 ^ b) / 10 ^ b
      In an equation for `calcFloatingNum':
          calcFloatingNum a b = truncate (a * 10 ^ b) / 10 ^ b
   |
10 | calcFloatingNum a b = truncate ( a * 10^b) /10^b

And if I try anyway it states:

ghci> calcFloatingNum 0.2345 2

<interactive>:1:1: error:
    Variable not in scope: calcFloatingNum :: t0 -> t1 -> t
ghci>

So the Signature might be the problem, however I can't seem to find the solution.

I tried converting the numbers with "fromInteger" and "toInteger", however it resulted in Error codes as well.

CodePudding user response:

Besides the things I mentioned in my comments, this question is really an exercise in following the types and in particular the floating and integral types.

Let's start off with the type signatures of the functions that you are attempting to use. I'll use concrete types to keep things simple.

truncate :: Double -> Int
(^) :: Int -> Int -> Int

As you can see these functions produce integers, while you want floats. So whenever we use these function we need to use fromIntegral :: Int -> Double to convert the result back into Double:

calcFloatingNum:: Double -> Int -> Double
calcFloatingNum a b = 
  fromIntegral (truncate (a * fromIntegral (10 ^ b))) / fromIntegral (10 ^ b)
  • Related