Advertisement
manojbaishya

truncate_digits

Oct 12th, 2020
2,047
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.62 KB | None | 0 0
  1. import decimal
  2.  
  3.  
  4. def truncate(num, lim):
  5.     """Truncates/pads a float f to n decimal places without rounding."""
  6.     snum = "{}".format(num)
  7.  
  8.     if 'e' in snum or 'E' in snum:
  9.         snum = "{0:f}".format(num)
  10.  
  11.     (intg, pt, dec) = snum.partition('.')
  12.  
  13.     numlen = len(intg) + len(dec)
  14.  
  15.     if len(intg) < lim:
  16.         if numlen >= lim:
  17.             diff = lim - len(intg)
  18.             fnum = intg + '.' + dec[0:diff]
  19.         else:
  20.             fnum = intg + '.' + dec + '0' * (lim - numlen)
  21.     elif len(intg) == lim:
  22.         fnum = intg
  23.     else:
  24.         fnum = intg[0:lim]
  25.  
  26.     return decimal.Decimal(fnum)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement