Is there a simple function to round a Double
or Float
to a specified number of digits? I've searched here and on Hoogle (for (Fractional a) => Int -> a -> a
), but haven't found anything.
Asked
Active
Viewed 1.4k times
22

amindfv
- 8,438
- 5
- 36
- 58
-
A float or double output doesn't make much sense... – Karoly Horvath Sep 16 '12 at 20:37
-
1I'd suggest something like: `(fromInteger $ round $ f * (10^n)) / (10.0^^n)` – aland Sep 16 '12 at 20:49
-
@KarolyHorvath: Is there a better output type? I don't know what else, say, 3.1415 could be represented as. – amindfv Sep 16 '12 at 20:52
-
@aland: This works perfectly; maybe you should write it as an answer. Is there really no rounding function (besides `round`) in the standard libraries, though? – amindfv Sep 16 '12 at 21:07
-
@amindfv I'm not very familiar with Haskell, but I haven't encountered similar functions in other languages' standard libraries. – aland Sep 16 '12 at 21:13
-
For example, in PHP you can write `round(3.1415, 2)`, and in Ruby >= 1.9, you can write `3.14159.round(2)` – amindfv Sep 16 '12 at 21:19
-
1@amindfv (re: "is there a better output type?") There's a few fixed-point number types on Hackage, or you could just use a poor-man's fixed-point represented as an `Integer`. – Daniel Wagner Sep 17 '12 at 00:50
-
3`Double` and `Float` are always binary fractions. If someone tells you that you can round them to a specified number of _decimal_ digits, they are lying. – Louis Wasserman Sep 17 '12 at 02:41
3 Answers
39
Not sure whether any standard function exists, but you can do it this way:
(fromInteger $ round $ f * (10^n)) / (10.0^^n)

aland
- 4,829
- 2
- 24
- 42
-
1Looks like noone's jumping in with a standard-library version, so I'm going to mark this as accepted -- works great; thanks. – amindfv Sep 17 '12 at 01:43
15
It depends on what you are going to do with the rounded number.
If you want to use it in calculations, you should use Data.Decimal
from Decimal
library.
If you want just to format the number nicely, you should use Text.Printf
from the standard library (base
package).

nponeccop
- 13,527
- 1
- 44
- 106
-1
λ: ((/100) $ fromIntegral $ round (0.006 * 100)) == 0.006
λ: False
λ: ((/100) $ fromIntegral $ round (0.06 * 100)) == 0.06
λ: True

Blkdev
- 7
- 1