Python Programming Exercises,
Gently Explained
147
# negative before returning it:
if isNegative:
return -integerNum
else:
return integerNum
Exercise #33: Comma-Formatted Numbers
def commaFormat(number):
# Convert the number to a string:
number = str(number)
# Remember the fractional part and remove it from the number, if any:
if '.' in number:
fractionalPart = number[number.index('.'):]
number = number[:number.index('.')]
else:
fractionalPart = ''
# Create a variable to hold triplets of digits and the
# comma-formatted string as it is built:
triplet = ''
commaNumber = ''
# Loop over the digits starting on the right side and going left:
for i in range(len(number) - 1, -1, -1):
# Add the digits to the triplet variable:
triplet = number[i] + triplet
# When the triplet variable has three digits, add it with a
# comma to the comma-formatted string:
if len(triplet) == 3:
commaNumber = triplet + ',' + commaNumber
# Reset the triplet variable back to a blank string:
triplet = ''
# If the triplet has any digits left over, add it with a comma
# to the comma-formatted string:
if triplet != '':
commaNumber = triplet + ',' + commaNumber
# Return the comma-formatted string:
return commaNumber[:-1] + fractionalPart
Dostları ilə paylaş: