You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on Aug 6, 2021. It is now read-only.
def trunc(number, num_digits=0):
"""Truncate a number to the specified number of digits."""
if isinstance(number, (int, float)):
# Simple case. We want to make sure to return an integer in this
# case.
if num_digits == 0:
return math.trunc(number)
return math.trunc(number * 10**num_digits) / 10**num_digits
else:
return ExcelError(
'#VALUE!', '{} must be a number. You gave me a {}'.format(
number, type(number)))
xlcalculator.evaluator.evaluator.TRUNC = trunc
xlfunctions.TRUNC = trunc
xlfunctions.SUPPORTED_FUNCTIONS['TRUNC'] = 'TRUNC'
Note that because you are importing all functions early in xlcalculator you have to register your function everywhere.
I would propose to create a proper functions object in which you can register new functions by reference instead of partial Python path.
class ExcelFunctions(dict):
def register(self, func, name=None):
if name is None:
name = func.__name__
self[name.upper()] = func
def __getattr__(self, name):
return self[name]
fn = ExcelFunctions()
# A quick decorator
def register(name=None):
def reg(func):
fn.register(func, name)
return reg
# Example use:
@register('TRUNC')
def trunc(arg):
return int(arg)
eval(model.cells['A1'].formula.python_code, locals={'fn': fn})
Implementation:
Note that because you are importing all functions early in xlcalculator you have to register your function everywhere.
I would propose to create a proper functions object in which you can register new functions by reference instead of partial Python path.