summaryrefslogtreecommitdiff
path: root/Utility/HumanNumber.hs
diff options
context:
space:
mode:
authorGravatar Joey Hess <joey@kitenet.net>2013-07-19 19:39:14 -0400
committerGravatar Joey Hess <joey@kitenet.net>2013-07-19 19:39:14 -0400
commitd3d9381f09fba70b0d622815b797358c6bcdc548 (patch)
tree38fcd594a788a56fc6f52552346f54f51ad3b2e1 /Utility/HumanNumber.hs
parent284970a49c77e8a410929231906766c538fe9269 (diff)
refactor and unify code
This fixes several bugs in both modules.
Diffstat (limited to 'Utility/HumanNumber.hs')
-rw-r--r--Utility/HumanNumber.hs21
1 files changed, 21 insertions, 0 deletions
diff --git a/Utility/HumanNumber.hs b/Utility/HumanNumber.hs
new file mode 100644
index 000000000..904135987
--- /dev/null
+++ b/Utility/HumanNumber.hs
@@ -0,0 +1,21 @@
+{- numbers for humans
+ -
+ - Copyright 2012-2013 Joey Hess <joey@kitenet.net>
+ -
+ - Licensed under the GNU GPL version 3 or higher.
+ -}
+
+module Utility.HumanNumber where
+
+{- Displays a fractional value as a string with a limited number
+ - of decimal digits. -}
+showImprecise :: RealFrac a => Int -> a -> String
+showImprecise precision n
+ | precision == 0 || remainder == 0 = show (round n :: Integer)
+ | otherwise = show int ++ "." ++ striptrailing0s (pad0s $ show remainder)
+ where
+ int :: Integer
+ (int, frac) = properFraction n
+ remainder = round (frac * 10 ^ precision) :: Integer
+ pad0s s = (take (precision - length s) (repeat '0')) ++ s
+ striptrailing0s = reverse . dropWhile (== '0') . reverse