Here are some examples on working with numbers.

Data types for numbers

In python there are three different datas available for handling numbers

  • int
  • float
  • Decimal

Converting from string

When working with numbers, a typical thing to do is to create them from string values:

Convert from string to int

def convert_to_int(s):
  try:
    print(int(s))
  except ValueError:
    print("Cannot convert to int")

Convert from string to float

def convert_to_float(s):
  try:
    print(float(s))
  except ValueError:
    print("Cannot convert to float")

Convert from string to Decimal

Decimals are handled slightly differently as compared to int and float. To use Decimals, the following imports are needed:

from decimal import Decimal
from decimal import DecimalException

…now it is possible to create a Decimal from a string value:

def convert_to_decimal(s):
  try:
    print(Decimal(s))
  except DecimalException:
    print("Cannot convert to Decimal")

Formatting numbers

There are numerous alternatives when it comes to formatting numbers. Some are listed below:

def format_number(number):
  print("{:.2f}".format(number))  # 4.86
  print("{:+.2f}".format(number)) # +4.86
  print("{:.0f}".format(number))  # 5
  print("{:0>2d}".format(5))      # 05
  print("{:,}".format(1000000))   # 1,000,000
  print("{:.2%}".format(number))  # 485.71%
  print("{:.2e}".format(number))  # 4.86e+00
  print("{:10d}".format(50))      #         50
  print("{:<10d}".format(50))     # 50
  print("{:^10d}".format(50))     #     50

Further resources

My python challenge