1

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.

4
  • 1
    If you get an error then your library will not be loaded, so none of the functions you define will be in scope. That explains the error you get in GHCi. Commented Nov 13, 2022 at 11:02
  • 1
    Your type signature says the function takes three inputs: Double, Int, and Int, but your definition only lists a and b as arguments. This seems unintentional. Commented Nov 13, 2022 at 11:07
  • 1
    I'd recommend using only a single floating point type. And Double is generally better supported, so I'd suggest changing the Float in your type signature to Double. Commented Nov 13, 2022 at 11:09
  • The first thing I would say is that if you truncate the number you have lost the information you need to round correctly. Commented Nov 13, 2022 at 20:02

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.