Permalink
Browse files

fix filesizeformat filter

  • Loading branch information...
1 parent 6336e77 commit d45431c6279de4d35be14d6110cc085cd636f036 @marcusti committed Aug 5, 2011
Showing with 14 additions and 10 deletions.
  1. +4 −4 jinja2/filters.py
  2. +10 −6 jinja2/testsuite/filters.py
View
@@ -337,7 +337,7 @@ def do_random(environment, seq):
return environment.undefined('No random item, sequence was empty.')
-def do_filesizeformat(value, binary=False):
+def do_filesizeformat(value, binary=False, precision=1):
"""Format the value like a 'human-readable' file size (i.e. 13 kB,
4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,
Giga, etc.), if the second parameter is set to `True` the binary
@@ -361,10 +361,10 @@ def do_filesizeformat(value, binary=False):
return "%d Bytes" % bytes
else:
for i, prefix in enumerate(prefixes):
- unit = base * base ** (i + 1)
+ unit = base ** (i + 2)
if bytes < unit:
- return "%.1f %s" % ((bytes / unit), prefix)
- return "%.1f %s" % ((bytes / unit), prefix)
+ return "%.*f %s" % (precision, base * bytes / unit, prefix)
+ return "%.*f %s" % (precision, base * bytes / unit, prefix)
def do_pprint(value, verbose=False):
@@ -77,16 +77,20 @@ def test_filesizeformat(self):
'{{ 1000000|filesizeformat }}|'
'{{ 1000000000|filesizeformat }}|'
'{{ 1000000000000|filesizeformat }}|'
- '{{ 100|filesizeformat(true) }}|'
'{{ 1000|filesizeformat(true) }}|'
- '{{ 1000000|filesizeformat(true) }}|'
- '{{ 1000000000|filesizeformat(true) }}|'
- '{{ 1000000000000|filesizeformat(true) }}'
+ '{{ 1024|filesizeformat(true) }}|'
+ '{{ 1048576|filesizeformat(true) }}|'
+ '{{ 1073741824|filesizeformat(true) }}|'
+ '{{ 1099511627776|filesizeformat(true) }}|'
+ '{{ 1984|filesizeformat(binary=true, precision=1) }}|'
+ '{{ 1984|filesizeformat(binary=true, precision=2) }}'
)
out = tmpl.render()
+ print out
assert out == (
- '100 Bytes|0.0 kB|0.0 MB|0.0 GB|0.0 TB|100 Bytes|'
- '1000 Bytes|1.0 KiB|0.9 MiB|0.9 GiB'
+ '100 Bytes|1.0 kB|1.0 MB|1.0 GB|1.0 TB|'
+ '1000 Bytes|1.0 KiB|1.0 MiB|1.0 GiB|1.0 TiB|'
+ '1.9 KiB|1.94 KiB'
)
def test_first(self):

0 comments on commit d45431c

Please sign in to comment.