2013-07-19 23:39:14 +00:00
|
|
|
{- numbers for humans
|
|
|
|
-
|
2021-07-30 13:56:04 +00:00
|
|
|
- Copyright 2012-2021 Joey Hess <id@joeyh.name>
|
2013-07-19 23:39:14 +00:00
|
|
|
-
|
2014-05-10 14:01:27 +00:00
|
|
|
- License: BSD-2-clause
|
2013-07-19 23:39:14 +00:00
|
|
|
-}
|
|
|
|
|
2019-11-21 19:38:06 +00:00
|
|
|
module Utility.HumanNumber (showImprecise) where
|
2013-07-19 23:39:14 +00:00
|
|
|
|
|
|
|
{- Displays a fractional value as a string with a limited number
|
|
|
|
- of decimal digits. -}
|
|
|
|
showImprecise :: RealFrac a => Int -> a -> String
|
|
|
|
showImprecise precision n
|
2021-07-30 13:56:04 +00:00
|
|
|
| precision == 0 || remainder' == 0 = show (round n :: Integer)
|
|
|
|
| otherwise = show int' ++ "." ++ striptrailing0s (pad0s $ show remainder')
|
2013-07-19 23:39:14 +00:00
|
|
|
where
|
|
|
|
int :: Integer
|
|
|
|
(int, frac) = properFraction n
|
|
|
|
remainder = round (frac * 10 ^ precision) :: Integer
|
2021-07-30 13:56:04 +00:00
|
|
|
(int', remainder')
|
|
|
|
-- carry the 1
|
|
|
|
| remainder == 10 ^ precision = (int + 1, 0)
|
|
|
|
| otherwise = (int, remainder)
|
2014-04-26 23:25:05 +00:00
|
|
|
pad0s s = replicate (precision - length s) '0' ++ s
|
2013-07-19 23:39:14 +00:00
|
|
|
striptrailing0s = reverse . dropWhile (== '0') . reverse
|