[Haskell-cafe] Problem with percentage function?
Chapman, Anthony Sergio
a.s.chapman.10 at aberdeen.ac.uk
Sun Apr 20 21:50:43 UTC 2014
Thank you very much, that worked a charm. The numbers crunching was done way before the printing so that's all I needed. Now it seems a bit peculiar to me that in your functions, you didn't define the input ie toPerc = printf "%.2f" . (*100) instead of toPerc number = printf "%.2f" . (*100)
Would you might pointing me in the right direction to understand why you didn't have to give it a variable input when defining the function?
Thanks again.
________________________________________
From: Haskell-Cafe <haskell-cafe-bounces at haskell.org> on behalf of Tom Ellis <tom-lists-haskell-cafe-2013 at jaguarpaw.co.uk>
Sent: 20 April 2014 22:45
To: haskell-cafe at haskell.org
Subject: Re: [Haskell-cafe] Problem with percentage function?
On Sun, Apr 20, 2014 at 09:12:29PM +0000, Chapman, Anthony Sergio wrote:
> -- Turns a number into a percentage
> toPerc :: Double -> Double
> toPerc x = 100*(myRound x 4)
> -- Rounds a number to s decimal points
> myRound n s = fromIntegral (round (n * factor)) / factor
> where factor = fromIntegral (10^s)
>
> I would it to round to 2 decimal places no matter what the size of the input is
>
> ei toPerc 0.22222222222222 --- = 22.22
> toPerc 0.22342222222222 --- = 22.34
>
> The problem is that what I actually get is 22.220000000000002
The other replies, whilst correct, have been a bit oblique to your question.
The upshot is you should do the rounding when displaying, not in the
floating point value itself.
import Text.Printf
toPerc :: Double -> String
toPerc = printf "%.2f" . (*100)
*Main> toPerc 0.22222222222222
"22.22"
*Main> toPerc 0.22342222222222
"22.34"
Tom
_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe at haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe
More information about the Haskell-Cafe
mailing list