diff --git a/tabulate.py b/tabulate.py index 0579fb3..ed8adec 100644 --- a/tabulate.py +++ b/tabulate.py @@ -5,6 +5,7 @@ from __future__ import print_function from __future__ import unicode_literals from collections import namedtuple +from decimal import Decimal import sys import re import math @@ -996,7 +997,14 @@ def _format(val, valtype, floatfmt, missingval="", has_invisible=True): formatted_val = format(float(raw_val), floatfmt) return val.replace(raw_val, formatted_val) else: - return format(float(val), floatfmt) + try: + if "f" in floatfmt and float('-inf') < float(val) < float('inf'): + val = Decimal(str(val)) + else: + val = float(val) + except (OverflowError, ValueError): + val = float(val) + return format(val, floatfmt) else: return "{0}".format(val) diff --git a/test/test_output.py b/test/test_output.py index eed4489..38f1766 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -1428,6 +1428,12 @@ def test_floatfmt_multi(): assert_equal(expected, result) +def test_floatfmt_precision(): + result = tabulate([["99999998999.999980", 1234.5, 1.2345678, "inf"]], floatfmt=".6f", tablefmt="plain") + expected = "99999998999.999980 1234.500000 1.234568 inf" + assert_equal(expected, result) + + def test_colalign_multi(): "Output: string columns with custom colalign" result = tabulate(