Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def number_to_string(num):
- '''
- @params
- num: Number
- @return
- string
- If num is a _really_ large number you may expect performance issues
- since there are N iterations to construct the new string.
- '''
- N = str(num)
- if not len(N):
- return ''
- if len(N) <= 3:
- return N
- float_section = N.split('.')
- if len(float_section) > 1:
- N = float_section[0] # Remove float for now
- negative = num < 0
- if negative:
- N = N[1::] # Remove negative symbol for now
- number_as_string = ''
- # The first comma will appear in the n-3th position in reverse
- # So we'll find the first comma, then we add an additional index
- # For every 3 characters in N
- commaIndex = range(
- len(N) - 3, 0, -3
- )
- # Then iterate in reverse because we made some assumptions earlier
- for i in reversed(range(len(N))):
- number_as_string = '{}{}'.format(
- '{}{}'.format(
- ',' if i in commaIndex else '', N[i]
- ), number_as_string
- )
- return '{}{}{}'.format(
- '-' if negative else '', number_as_string,
- '.{}'.format(float_section[1]) if len(float_section) > 1 else ''
- )
- print (number_to_string(0))
- print (number_to_string(1234))
- print (number_to_string(12345))
- print (number_to_string(123456))
- print (number_to_string(1234567))
- print (number_to_string(12345678))
- print (number_to_string(1234))
- print (number_to_string(123))
- print (number_to_string(1))
- print (number_to_string(123456789))
- print (number_to_string(1123456789))
- print (number_to_string(-1))
- print (number_to_string(-1.2))
- print (number_to_string(-1234.2))
Add Comment
Please, Sign In to add comment