Python number formatting examples

Last updated:
Table of Contents

WIP Alert This is a work in progress. Current information is correct but more content may be added in the future.

Difference between truncating and rounding a number

View notebook here

PLEASE NOTE: Formatting means representing a number as a String!

Round float to 2 decimal places

>> '5.40'

Truncate float at 2 decimal places

This is just one way to do it. There probably are others.

This will drop digits after the second decimal place (if there are any).

import re

# see the notebook for a generalized version
def truncate(num):
    return re.sub(r'^(\d+\.\d{,2})\d*$',r'\1',str(num))

>> '8.49'

>> '8.49'

>> '8.4'

>> '8.0'

>> '8'

Left padding with zeros

E.g. make the full size equal to 9 (all included), fill with zeros to the left:

>> '00003.499'

Right padding with zeros

E.g. make the full size equal to 11, fill with zeros to the right:

>> '3.499000000'

Use commas as thousands separator

> '100,000'


Dialogue & Discussion