Skip to content

Commit

Permalink
Fix floatfmt always using 'g' formatting with to_str
Browse files Browse the repository at this point in the history
  • Loading branch information
alugowski committed Sep 12, 2023
1 parent 425071a commit 8492d98
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 9 deletions.
1 change: 1 addition & 0 deletions matrepr/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ def get(self, **kwargs):
ret.set_precision(ret.precision)
elif isinstance(ret.floatfmt, str):
fmt_str = ret.floatfmt
ret.floatfmt_str = fmt_str
ret.floatfmt = lambda f: format(f, fmt_str)

# validate
Expand Down
14 changes: 7 additions & 7 deletions matrepr/list_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,6 @@ def pprint(self, obj, is_index=False):
else:
obj = self.fill_value

if isinstance(obj, int) and is_index:
return str(obj)

if isinstance(obj, (int, float)):
formatted = self.floatfmt(obj)
return obj if repr(obj) == formatted else formatted

if type(obj).__module__ == "numpy":
# numpy is installed
import numpy as np
Expand All @@ -71,6 +64,13 @@ def pprint(self, obj, is_index=False):
# do not fall through to the regular numpy driver below because of missing multiline support in tabular.
return _single_line(str(obj))

if isinstance(obj, int) and is_index:
return str(obj)

if isinstance(obj, (int, float)):
formatted = self.floatfmt(obj)
return obj if repr(obj) == formatted else formatted

if isinstance(obj, complex):
sign = "-" if obj.imag < 0 else "+"
r = str(self.pprint(obj.real)).replace("e+", "e")
Expand Down
9 changes: 7 additions & 2 deletions matrepr/string_formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,10 +205,14 @@ def _to_tabulate_args(mat: Any, is_tensor, options, tab_extra_args) -> Tuple[Dic
row_labels_txt = _format_row_labels(_labels_to_str(row_labels), has_header=has_header, tf=matrix_format)

# collect floatfmt argument
if isinstance(options.floatfmt, str):
disable_numparse = tab_extra_args.pop("disable_numparse", False)
if hasattr(options, "floatfmt_str"):
floatfmt = options.floatfmt_str
elif isinstance(options.floatfmt, str):
floatfmt = options.floatfmt
else:
floatfmt = f".{options.precision}g"
disable_numparse = True # the numbers are already formatted; leave them as is
floatfmt = "g"

# column alignment
index_cols = set(mat.columns_as_index())
Expand All @@ -229,6 +233,7 @@ def _to_tabulate_args(mat: Any, is_tensor, options, tab_extra_args) -> Tuple[Dic
"tablefmt": matrix_format,
"floatfmt": floatfmt,
"colalign": colalign,
"disable_numparse": disable_numparse,
**tab_extra_args
}

Expand Down

0 comments on commit 8492d98

Please sign in to comment.