I have a simple question how can i show the number 12045678 as 12,045,678 i.e automatically show in american format in jython
so 12345 should be 12,345 and 1234567890 should be 1,234,567,890 and so on.
Than开发者_如何转开发ks everyone for your help.
See the official documentation, in particular 7.1.3.1. Format Specification Mini-Language and in particular:
'n' Number.
This is the same as 'g', except that it uses the current locale setting to insert the appropriate number separator characters.
See How to print number with commas as thousands separators?
You can use a function like this:
def numberToPrettyString(n):
"""Converts a number to a nicely formatted string.
Example: 6874 => '6,874'."""
l = []
for i, c in enumerate(str(n)[::-1]):
if i%3==0 and i!=0:
l += ','
l += c
return "".join(l[::-1])
prior to 2.6 there is no built-in function
this is the easiest one I've found
def splitthousands(s, sep=','):
if len(s) <= 3: return s
return splitthousands(s[:-3], sep) + sep + s[-3:]
splitthousands('123456')
123,456
精彩评论