Skip to content

Commit 5373ebf

Browse files
mvadariastanin
andauthored
fix #176 - implement Decimal fixed-point support
* fix decimal precision issue * fix other float to Decimal * fix float precision * add test * clean up * fix bug * expand test * fix test to get around weird precision issues in python2.7 * lint * respond to comments --------- Co-authored-by: Sergey Astanin <s.astanin@gmail.com>
1 parent 8f32086 commit 5373ebf

2 files changed

Lines changed: 14 additions & 0 deletions

File tree

tabulate/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import warnings
1414
from collections import namedtuple
1515
from collections.abc import Iterable, Sized
16+
from decimal import Decimal
1617
from html import escape as htmlescape
1718
from itertools import chain, zip_longest as izip_longest
1819
from functools import reduce, partial
@@ -1356,6 +1357,8 @@ def _format(val, valtype, floatfmt, intfmt, missingval="", has_invisible=True):
13561357
else:
13571358
if isinstance(val, str) and "," in val:
13581359
val = val.replace(",", "") # handle thousands-separators
1360+
if isinstance(val, Decimal):
1361+
return format(val, floatfmt)
13591362
try:
13601363
return format(float(val), floatfmt)
13611364
except (ValueError, TypeError):

test/test_output.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Test output of the various forms of tabular data."""
22

3+
from decimal import Decimal
34
from pytest import mark
45

56
from common import assert_equal, raises, skip, check_warnings
@@ -2857,6 +2858,16 @@ def test_floatfmt_multi():
28572858
assert_equal(expected, result)
28582859

28592860

2861+
def test_floatfmt_decimal():
2862+
result = tabulate(
2863+
[[Decimal("99999998999.999980"), 1234.5, 1.2345678, "inf"]],
2864+
floatfmt=".6f",
2865+
tablefmt="plain",
2866+
)
2867+
expected = "99999998999.999980 1234.500000 1.234568 inf"
2868+
assert_equal(expected, result)
2869+
2870+
28602871
def test_colalign_multi():
28612872
"Output: string columns with custom colalign"
28622873
result = tabulate([["one", "two"], ["three", "four"]], colalign=("right",), tablefmt="plain")

0 commit comments

Comments
 (0)