Skip to content

Commit 3dcf0ad

Browse files
committed
🐛 return None when rounding 0
1 parent 39072f5 commit 3dcf0ad

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

plotly_resampler/figure_resampler/utils.py

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ def timedelta_to_str(td: pd.Timedelta) -> str:
114114
-------
115115
str:
116116
The tight string bounds of format '$d-$h$m$s.$ms'.
117+
If the timedelta is negative, the string starts with 'NEG'.
117118
118119
"""
119120
out_str = ""
@@ -153,19 +154,46 @@ def timedelta_to_str(td: pd.Timedelta) -> str:
153154
def round_td_str(td: pd.Timedelta) -> str:
154155
"""Round a timedelta to the nearest unit and convert to a string.
155156
157+
Parameters
158+
----------
159+
td : pd.Timedelta
160+
The timedelta to round.
161+
162+
Returns
163+
-------
164+
str
165+
The rounded timedelta as a string.
166+
If the timedelta is == 0, None is returned.
167+
156168
.. seealso::
157169
:func:`timedelta_to_str`
170+
158171
"""
159172
for t_s in ("D", "H", "min", "s", "ms", "us", "ns"):
160173
if td > 0.95 * pd.Timedelta(f"1{t_s}"):
161174
return timedelta_to_str(td.round(t_s))
162175

163176

164177
def round_number_str(number: float) -> str:
178+
"""Round a number to the nearest unit and convert to a string.
179+
180+
Parameters
181+
----------
182+
number : float
183+
The number to round.
184+
185+
Returns
186+
-------
187+
str
188+
The rounded number as a string.
189+
If the number is <= 0, None is returned.
190+
191+
"""
165192
if number > 0.95:
166193
for unit, scaling in (("M", int(1e6)), ("k", int(1e3))):
167194
if number / scaling > 0.95:
168195
return f"{round(number / scaling)}{unit}"
169196
return str(round(number))
170-
# we have a number < 1 --> round till nearest non-zero digit
171-
return str(round(number, 1 + abs(int(math.log10(number)))))
197+
if number > 0: # avoid log10(0)
198+
# we have a number between 0-0.95 -> round till nearest non-zero digit
199+
return str(round(number, 1 + abs(int(math.log10(number)))))

tests/test_utils.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ def test_timedelta_to_str():
8686
assert round_td_str(pd.Timedelta("1128.9us")) == "1ms"
8787
assert round_td_str(pd.Timedelta("128.9us")) == "129us"
8888
assert round_td_str((pd.Timedelta("14ns"))) == "14ns"
89+
assert round_td_str((pd.Timedelta("0ns"))) == None
8990

9091

9192
def test_round_int_str():
@@ -109,3 +110,4 @@ def test_round_int_str():
109110
assert round_number_str(950_001) == "1M"
110111
assert round_number_str(1_950_001) == "2M"
111112
assert round_number_str(111_950_001) == "112M"
113+
assert round_number_str(0) == None

0 commit comments

Comments
 (0)