Advertisement
Guest User

Untitled

a guest
May 26th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.65 KB | None | 0 0
  1. def commas(x):
  2.  
  3.     x = round(x, 3)
  4.     if x == round(x):
  5.         x = int(x)
  6.  
  7.     sgn = x < 0
  8.     if sgn:
  9.         x = -x
  10.     s = str(x)
  11.     a = s.split('.')
  12.     s = a[0]
  13.     s = ''.join(reversed(list(s)))
  14.     res = ''
  15.     for i in range(len(s)):
  16.         res += s[i]
  17.         if i % 3 == 2 and i != len(s) - 1:
  18.             res += ','
  19.     res = ''.join(reversed(list(res)))
  20.     if len(a) == 2:
  21.         res += '.' + a[1]
  22.  
  23.     if sgn:
  24.         res = '-' + res
  25.     return res
  26.  
  27.  
  28. assert commas(1) == "1"
  29. assert commas(1000) == "1,000"
  30. assert commas(100.2346) == "100.235"
  31. assert commas(1000000000.23) == "1,000,000,000.23"
  32. assert commas(-999.9999) == "-1,000"
  33. assert commas(-1234567.0001236) == "-1,234,567"
  34. print("TEST PASSED")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement