[Haskell-beginners] how to print a floating-point number?

Sergei Winitzki winitzki at gmail.com
Thu Jan 8 16:15:39 EST 2009

Great, it worked! I was trying to convert 1.0e12 to float, thinking
that the integer variable will be coerced automatically to float. The
correct code is

print ( (fromInteger time) / 1.0e12 )

thanks for the explanations!

On Thu, Jan 8, 2009 at 7:28 PM, Daniel Fischer <daniel.is.fischer at web.de> wrote:
> Am Donnerstag, 8. Januar 2009 17:45 schrieb Sergei Winitzki:
>> Subject: how to print a floating-point number?
>> hi,
>> I am very new to Haskell. I am trying to benchmark the CPU time needed
>> for a computation, and I can't figure out how to print a
>> floating-point number.
>> My code is as follows, and I expected it to work:
>> import System.CPUTime
>> main = do
>>        let result = some_computation
>>        print result
>>        time <- getCPUTime          -- this is an Integer that needs
>> to be divided by 1e12 to get time in seconds
>>        print (time / 1.0e12)           -- I want this to print a
>> floating-point number
> You have to convert the Integer to a floating point number first, use
> fromInteger
> or
> fromIntegral
> for that. Haskell does not do automatic conversion between numeric types.
>> But this does not compile.
>> Error message:    No instance for (Fractional Integer)
>>      arising from use of `/' at fact1.hs:18:15-28
>>    Possible fix: add an instance declaration for (Fractional Integer)
>>    In the first argument of `print', namely `(time1 / 1.0e12)'
>>  I thought this should work because e.g. 12 / 7 evaluates to
>> 1.7142857142857142 in ghci.
> That is because numeric *literals* are polymorphic, as they are parsed as e.g.
> "fromInteger 12" if it's an integer literal or "fromRational 3.24" if it's a
> non-integer literal.
>> I understand this is some problem with types, but surely it is fixed
>> not by adding any instance declarations but perhaps by using some
>> Prelude or Numeric function. But which one?
>>  I tried everything I could find in the documentation: showFloat,
>> adding ::Float everywhere, adding fromIntegral, etc.etc. - nothing
>> works. All the books and the tutorials I looked at seem to discuss at
>> length such nice things as Fibonacci numbers and recursive factorial
>> functions rather than a practical problem like this.
> When you are looking for a function, it's a good idea to ask hoogle
> (http://haskell.org/hoogle/) for a function of appropriate type. Asking for a
> function Integer -> Double, the abovementioned are results 1 and 3.
>> help will be much appreciated!
>> Sergei
> HTH,
> Daniel

More information about the Beginners mailing list