How to format decimal number in Python
I got a question about formating decimal number in Python by adding comma in appropriate positions. The most recommend approach is to use built-in locale support. In my opinion, this is not too difficult to implement and there are many approaches. I just want to give an example here as a guideline.
#!/usr/bin/env python def comma(d): s = '%0.2f' % d a,b = s.split('.') l = [] while len(a) > 3: l.insert(0,a[-3:]) a = a[0:-3] if a: l.insert(0,a) return ','.join(l)+'.'+b if __name__ == '__main__': print comma(1123456.12)
- sugree's blog
- 4639 reads
Post new comment