Guest User

Untitled

a guest
Jan 18th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. def number_to_string(num):
  2. '''
  3. @params
  4. num: Number
  5. @return
  6. string
  7.  
  8. If num is a _really_ large number you may expect performance issues
  9. since there are N iterations to construct the new string.
  10.  
  11. '''
  12. N = str(num)
  13. if not len(N):
  14. return ''
  15. if len(N) <= 3:
  16. return N
  17.  
  18. float_section = N.split('.')
  19. if len(float_section) > 1:
  20. N = float_section[0] # Remove float for now
  21.  
  22. negative = num < 0
  23. if negative:
  24. N = N[1::] # Remove negative symbol for now
  25.  
  26. number_as_string = ''
  27.  
  28. # The first comma will appear in the n-3th position in reverse
  29. # So we'll find the first comma, then we add an additional index
  30. # For every 3 characters in N
  31. commaIndex = range(
  32. len(N) - 3, 0, -3
  33. )
  34.  
  35. # Then iterate in reverse because we made some assumptions earlier
  36. for i in reversed(range(len(N))):
  37. number_as_string = '{}{}'.format(
  38. '{}{}'.format(
  39. ',' if i in commaIndex else '', N[i]
  40. ), number_as_string
  41. )
  42.  
  43. return '{}{}{}'.format(
  44. '-' if negative else '', number_as_string,
  45. '.{}'.format(float_section[1]) if len(float_section) > 1 else ''
  46. )
  47.  
  48. print (number_to_string(0))
  49. print (number_to_string(1234))
  50. print (number_to_string(12345))
  51. print (number_to_string(123456))
  52. print (number_to_string(1234567))
  53. print (number_to_string(12345678))
  54. print (number_to_string(1234))
  55. print (number_to_string(123))
  56. print (number_to_string(1))
  57. print (number_to_string(123456789))
  58. print (number_to_string(1123456789))
  59.  
  60. print (number_to_string(-1))
  61. print (number_to_string(-1.2))
  62. print (number_to_string(-1234.2))
Add Comment
Please, Sign In to add comment