Advertisement
DeaD_EyE

roundk

Apr 16th, 2023
997
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.70 KB | None | 0 0
  1. def roundk(value: float | int, digits: int | None = None) -> float | int:
  2.     if not isinstance(value, (float, int)):
  3.         raise NotImplementedError("Only float is implemented")
  4.  
  5.     def iceil():
  6.         return (value // 10 + 1) * 10
  7.  
  8.     def ifloor():
  9.         return (value // 10) * 10
  10.  
  11.     def do_iceil():
  12.         return (value % 10) >= 5
  13.  
  14.     return_type = int if digits is None or isinstance(value, int) else float
  15.     digits = digits or 0
  16.  
  17.     to_int = 10 ** (digits + 1)
  18.     to_float = 10 ** (-digits - 1)
  19.     value = int(value * to_int)
  20.  
  21.     if do_iceil():
  22.         return return_type(iceil() * to_float)
  23.     else:
  24.         return return_type(ifloor() * to_float)
  25.  
  26.  
  27. roundk(155.4, -1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement