have humanize_size round down rather than up

rounding up can end up showing a free size for a disk that is larger than the
actual free size...
This commit is contained in:
Michael Hudson-Doyle 2018-03-22 14:12:41 +13:00
parent e61eb454cf
commit af67c7074c
3 changed files with 24 additions and 4 deletions

View File

@ -34,11 +34,14 @@ class FS:
def humanize_size(size):
size = abs(size)
if size == 0:
return "0B"
p = math.floor(math.log(size, 2) / 10)
return "%.3f%s" % (size / math.pow(1024, p), HUMAN_UNITS[int(p)])
p = int(math.floor(math.log(size, 2) / 10))
# We want to truncate the non-integral part, not round to nearest.
s = "{:.17f}".format(size / 2**(10*p))
i = s.index('.')
s = s[:i+4]
return s + HUMAN_UNITS[int(p)]
def dehumanize_size(size):

View File

@ -0,0 +1 @@
#

View File

@ -1,7 +1,23 @@
import unittest
from subiquity.models.filesystem import dehumanize_size
from subiquity.models.filesystem import dehumanize_size, humanize_size
class TestHumanizeSize(unittest.TestCase):
basics = [
('1.000M', 2**20),
('1.500M', 2**20+2**19),
('1.500M', 2**20+2**19),
('1023.000M', 1023*2**20),
('1.000G', 1024*2**20),
]
def test_basics(self):
for string, integer in self.basics:
with self.subTest(input=string):
self.assertEqual(string, humanize_size(integer))
class TestDehumanizeSize(unittest.TestCase):