snippetpythonModerate
Format a number to include commas
Viewed 0 times
includeformatnumbercommas
Problem
This is my attempt to format a number and put commas where appropriate. I was wondering if this could be done in a simpler way.
It's used by calling
It's used by calling
format_string_number("123456789") and prints 123,456,789.def format_string_number(st):
inputVal = list(st)
inputVal.reverse()
returnVal = []
for index, value in enumerate(inputVal):
returnVal.insert(0,value)
if (index+1) %3 == 0:
returnVal.insert(0,",")
if returnVal[0] == ",":
returnVal.pop(0)
print("".join(returnVal))Solution
A few comments:
Also, as pointed out in the comments, this is handled by
- It seems odd to write a function for formatting a number that takes a string as an argument;
- Your function doesn't currently deal with
floatnumbers correctly (and, as it takes a string argument, you can't easily checkisinstance(arg, int));
- Your function
prints the output rather thanreturning it, severely limiting its usefulness; and
- You aren't compliant with the style guide.
Also, as pointed out in the comments, this is handled by
format already, and can be used in str.format too:>>> "Number: {:,}".format(123456.789)
'Number: 123,456.789'Code Snippets
>>> "Number: {:,}".format(123456.789)
'Number: 123,456.789'Context
StackExchange Code Review Q#63398, answer score: 11
Revisions (0)
No revisions yet.