Skip to content
This repository
Browse code

Fixed do_filesizeformat to actually calculate correctly, fixes #59

  • Loading branch information...
commit 7d268bef0e8f3f12c0acb90f30d67726a3e3f261 1 parent 898975d
Christopher Grebs authored
8  jinja2/filters.py
@@ -361,10 +361,10 @@ def do_filesizeformat(value, binary=False):
361 361
         return '%d Bytes' % bytes
362 362
     else:
363 363
         for i, prefix in enumerate(prefixes):
364  
-            unit = base ** (i + 1)
365  
-            if bytes <= unit:
366  
-                return '%.1f %s' % ((bytes / unit), prefix)
367  
-        return '%.1f %s' % ((bytes / unit), prefix)
  364
+            unit = base ** (i + 2)
  365
+            if bytes < unit:
  366
+                return '%.1f %s' % ((base * bytes / unit), prefix)
  367
+        return '%.1f %s' % ((base * bytes / unit), prefix)
368 368
 
369 369
 
370 370
 def do_pprint(value, verbose=False):
20  jinja2/testsuite/filters.py
@@ -86,9 +86,27 @@ def test_filesizeformat(self):
86 86
         out = tmpl.render()
87 87
         self.assert_equal(out, (
88 88
             '100 Bytes|1.0 kB|1.0 MB|1.0 GB|1.0 TB|100 Bytes|'
89  
-            '1000 Bytes|1.0 MiB|0.9 GiB|0.9 TiB'
  89
+            '1000 Bytes|976.6 KiB|953.7 MiB|931.3 GiB'
90 90
         ))
91 91
 
  92
+    def test_filesizeformat_issue59(self):
  93
+        tmpl = env.from_string(
  94
+            '{{ 300|filesizeformat }}|'
  95
+            '{{ 3000|filesizeformat }}|'
  96
+            '{{ 3000000|filesizeformat }}|'
  97
+            '{{ 3000000000|filesizeformat }}|'
  98
+            '{{ 3000000000000|filesizeformat }}|'
  99
+            '{{ 300|filesizeformat(true) }}|'
  100
+            '{{ 3000|filesizeformat(true) }}|'
  101
+            '{{ 3000000|filesizeformat(true) }}'
  102
+        )
  103
+        out = tmpl.render()
  104
+        self.assert_equal(out, (
  105
+            '300 Bytes|3.0 kB|3.0 MB|3.0 GB|3.0 TB|300 Bytes|'
  106
+            '2.9 KiB|2.9 MiB'
  107
+        ))
  108
+
  109
+
92 110
     def test_first(self):
93 111
         tmpl = env.from_string('{{ foo|first }}')
94 112
         out = tmpl.render(foo=range(10))

0 notes on commit 7d268be

Please sign in to comment.
Something went wrong with that request. Please try again.