Skip to content
Snippets Groups Projects
Commit ccca30bb authored by Alan De Smet's avatar Alan De Smet
Browse files

Add missed file

parent e01812f1
No related branches found
No related tags found
No related merge requests found
# python3
def roundtozero(value, step = None, offset = None):
""" Round value toward zero to nearest step
If step is None, step is type(value)(1)
If offset is None, step is type(value)()
Should work with any number-like that supports addition, subtraction,
division (returning a float), and multiplication against an integer.
Possible return values should always be some form of
"step*X+offset" for an integer X.
>>> from csppfetch.roundtozero import roundtozero
>>> roundtozero(3.14)
3.0
>>> roundtozero(10,3)
9
>>> roundtozero(10,3,2)
8
>>> roundtozero(-10,3)
-9
>>> roundtozero(-10,3,2)
-10
>>> f"{roundtozero(1, 0.3):.5f}" # float math: 0.3*3 == 0.8999...
'0.90000'
>>> import datetime
>>> def delthour(h): return datetime.timedelta(hours=h)
>>> def as_hours(x): return x.total_seconds() /(60*60)
>>> as_hours(roundtozero(delthour(100)))
96.0
>>> as_hours(roundtozero(delthour(100), delthour(9)))
99.0
>>> as_hours(roundtozero(delthour(100), delthour(20), delthour(30)))
90.0
"""
try:
if step is None: step = type(value)(1)
except:
raise ValueError("roundtozero: Unable to construct a default step using type(value)(1); you'll need to pass step is explicitly.")
try:
if offset is None: offset = type(value)()
except:
raise ValueError("roundtozero: Unable to construct a default step using type(value)(); you'll need to pass step is explicitly.")
offset_value = value - offset
increments = int(offset_value / step)
rounded_value = (increments * step) + offset
return rounded_value
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment