Fix a rounding bug in display of data sizes
Eg, showImprecise 1 1.99 returned "1.1" rather than "2". The 9 rounded upward to 10, and that was wrongly used as the decimal, rather than carrying the 1. Sponsored-by: Jack Hill on Patreon
This commit is contained in:
parent
1c4d6dee90
commit
66089e97de
4 changed files with 80 additions and 3 deletions
|
@ -1,6 +1,6 @@
|
|||
{- numbers for humans
|
||||
-
|
||||
- Copyright 2012-2013 Joey Hess <id@joeyh.name>
|
||||
- Copyright 2012-2021 Joey Hess <id@joeyh.name>
|
||||
-
|
||||
- License: BSD-2-clause
|
||||
-}
|
||||
|
@ -11,11 +11,15 @@ module Utility.HumanNumber (showImprecise) where
|
|||
- 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)
|
||||
| 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
|
||||
(int', remainder')
|
||||
-- carry the 1
|
||||
| remainder == 10 ^ precision = (int + 1, 0)
|
||||
| otherwise = (int, remainder)
|
||||
pad0s s = replicate (precision - length s) '0' ++ s
|
||||
striptrailing0s = reverse . dropWhile (== '0') . reverse
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue