Skip to content

Commit e74e5cb

Browse files
AntonioAndrauesTomAugspurger
AntonioAndraues
andcommitted
BUG: set_precision format fixed (#13257)
Co-Authored-By: Tom Augspurger <[email protected]>
1 parent 19c8fad commit e74e5cb

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

pandas/io/formats/style.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,8 @@ def __init__(
156156

157157
def default_display_func(x):
158158
if is_float(x):
159-
return "{:>.{precision}g}".format(x, precision=self.precision)
159+
display_format = "{0:.{precision}f}".format(x, precision=self.precision)
160+
return display_format
160161
else:
161162
return x
162163

pandas/tests/io/formats/test_style.py

+26
Original file line numberDiff line numberDiff line change
@@ -1157,6 +1157,32 @@ def test_display_format_raises(self):
11571157
with pytest.raises(TypeError):
11581158
df.style.format(True)
11591159

1160+
def test_display_set_precision(self):
1161+
df = pd.DataFrame(data=[[1.0, 2.0090], [3.2121, 4.566]], columns=["a", "b"])
1162+
s = Styler(df)
1163+
1164+
ctx = s.set_precision(1)._translate()
1165+
1166+
assert s.precision == 1
1167+
assert ctx["body"][0][1]["display_value"] == "1.0"
1168+
assert ctx["body"][0][2]["display_value"] == "2.0"
1169+
assert ctx["body"][1][1]["display_value"] == "3.2"
1170+
assert ctx["body"][1][2]["display_value"] == "4.6"
1171+
1172+
ctx = s.set_precision(2)._translate()
1173+
assert s.precision == 2
1174+
assert ctx["body"][0][1]["display_value"] == "1.00"
1175+
assert ctx["body"][0][2]["display_value"] == "2.01"
1176+
assert ctx["body"][1][1]["display_value"] == "3.21"
1177+
assert ctx["body"][1][2]["display_value"] == "4.57"
1178+
1179+
ctx = s.set_precision(3)._translate()
1180+
assert s.precision == 3
1181+
assert ctx["body"][0][1]["display_value"] == "1.000"
1182+
assert ctx["body"][0][2]["display_value"] == "2.009"
1183+
assert ctx["body"][1][1]["display_value"] == "3.212"
1184+
assert ctx["body"][1][2]["display_value"] == "4.566"
1185+
11601186
def test_display_subset(self):
11611187
df = pd.DataFrame([[0.1234, 0.1234], [1.1234, 1.1234]], columns=["a", "b"])
11621188
ctx = df.style.format(

0 commit comments

Comments
 (0)