[Haskell-cafe] Problem with percentage function?
Bob Ippolito
bob at redivi.com
Sun Apr 20 21:21:10 UTC 2014
The problem is the type Double, which can not exactly represent numbers
such as 0.1. You would have this same issue in any language where you're
using binary floating point.
How to work around this really depends on the use case. There are many
approaches, such as using a type that can exactly represent all of the
numbers in the domain you're working with, or just doing this sort of
rounding on output.
http://floating-point-gui.de/
On Sun, Apr 20, 2014 at 2:12 PM, Chapman, Anthony Sergio <
a.s.chapman.10 at aberdeen.ac.uk> wrote:
> Good evening everyone.
>
> I've made a percentage function for my application (with help from the
> internet) which is as follows.
>
> -- 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
>
> If anyone has any suggestions on how to solve this problem or know of a
> different/better way to convert to percentage please let me know.
>
> Thanks
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20140420/66070c6f/attachment.html>
More information about the Haskell-Cafe
mailing list