#!/usr/bin/env python # coding: utf-8 # In[1]: from platform import python_version python_version() # # View the original blog post at [http://queirozf.com/entries/python-number-formatting-examples](http://queirozf.com/entries/python-number-formatting-examples) # ## format float as integer # In[3]: '{:.0f}'.format(8.0) # In[2]: '{:.0f}'.format(8.99) # ## round to 2 decimal places # In[2]: '{:.2f}'.format(8.499) # ## format float as percentage # In[3]: '{:.2f}%'.format(10.12345) # ## truncate to at most 2 decimal places # # turn it into a string then replace everything after the second digit after the point # In[4]: import re def truncate(num,decimal_places): dp = str(decimal_places) return re.sub(r'^(\d+\.\d{,'+re.escape(dp)+r'})\d*$',r'\1',str(num)) # In[5]: truncate(8.499,decimal_places=2) # In[6]: truncate(8.49,decimal_places=2) # In[7]: truncate(8.4,decimal_places=2) # In[8]: truncate(8,decimal_places=2) # ## left padding with zeros # In[9]: # make the total string size AT LEAST 9 (including digits and points), fill with zeros to the left '{:0>9}'.format(3.499) # In[10]: # make the total string size AT LEAST 2 (all included), fill with zeros to the left '{:0>2}'.format(3) # ## right padding with zeros # # # In[11]: # make the total string size AT LEAST 11 (including digits and points), fill with zeros to the RIGHT '{:<011}'.format(3.499) # ## comma separators # In[12]: "{:,}".format(100000) # ## variable interpolation and f-strings # In[15]: num = 1.12745 formatted = f"{num:.2f}" formatted # In[ ]: