ugly doubles - why 2.9000000000000004 instead of 2.9?

haskell

Solution

How do I tell ghci to not do that, and show the results of Operations on Doubles just as any other programming language (and calculator) would and just as every 15 year old would write them?

Since those results are the actual results GHCI (and your standard calculator*) calculates you cannot change the internal representation of the result (see TNI's answer). Since you want to show only a fixed number of decimals it's more a matter of the presentation (compare to `printf("%f.2",...)` in C).

A solution to this can be found in https://stackoverflow.com/a/2327801/1139697. It can be applied like this:

import Numeric
fixedN :: (RealFloat b) => Int -> b -> String
fixedN a b = showFFloat (Just a) b ""

map (fixedN 2 . (-)2.3) [4.0, 3.8, 5.2, 6.4, 1.3, 8.3, 13.7, 9.0, 7.5, 2.4]
-- result: ["-1.70","-1.50","-2.90","-4.10","1.00","-6.00",...]

Note that this won't be feasible if you want to continue calculation. If you want exact arithmetic, you're better of by using `Rationals` anyway. Don't forget that your input should be rational aswell in this case.

* yes, even your standard calculator does the same thing, the only reason you don't see it is the fixed presentation, it cannot show more than a fixed number of decimals.

Problem

when I do 5.2 - 2.3 in ghci I'll get 2.9000000000000004 instead of 2.9. Also such ugly (and for a human WRONG) results shows up on other places when working with Double or Float. Why does this happen? (this is just for curiosity, not my real question) My real question: How do I tell ghci to not do that, and show the results of Operations on Doubles just as any other programming language (and calculator) would and just as every 15 year old would write them? This is just so annoying when I use ghci as a nice calculator and work on lists on which I perform such operations. ``` map ((-)2.3) [4.0, 3.8, 5.2, 6.4, 1.3, 8.3, 13.7, 9.0, 7.5, 2.4] [-1.7000000000000002,-1.5,-2.9000000000000004,-4.1000000000000005,0.9999999999999998,-6.000000000000001,-11.399999999999999,-6.7,-5.2,-0.10000000000000009] ``` This just doesn't help when using the numbers on a piece of paper afterwards Thanks in advance :)

Original source

Related problems