Skip to content

Python Numbers

How to convert floating-point numbers to integers in Python using explicit type conversion with int(), handling truncation and precision limitations.

Python datatypes available are integers, floating-point numbers, and complex numbers.

In addition, there are also specific modules for performing decimal calculations and operations with fractions.

Number Datatype in Python

Python datatypes available are integers, floating-point numbers, and complex numbers. They are defined as int, float, and complex classes in Python.

  • Integers and floating points are separated by the presence or absence of a decimal point.
  • complex numbers are written in the form x + yj, where x is the real part and y is the imaginary part.
  • A floating-point number is accurate up to 15 decimal places.

Prefixes to specify the number system

The number system used for variables is the decimal system, unless explicitly changed.

In fact, developers may also need to work with binary (base 2), hexadecimal (base 16) and octal (base 8) number systems.

In Python, it is possible to represent these numbers by appropriately prefixing the number.

Number System Prefix
Binary 0b or 0B
Octal 0o or 0O
Hexadecimal 0x or 0X

For example:

print(0b1111011)   # 123
print(0xA3 + 0b10) # 165 (163 + 2)
print(0o12)        # 10

type() and isinstance() functions

The type() function is used to know what class a variable or value belongs to, and the isinstance() function is used to check if it belongs to a particular class.

For example

print(type(10))    # <class 'int'>

print(type(12.3))  # <class 'float'>

a = 1+2j
print(a + 3)       # (4+2j)
print(isinstance(a, complex))  # True

Output

<class 'int'>
<class 'float'>
(4+2j)
True

Type Conversion

It is possible to convert one type of number to another. This operation is also known as coercion.

Coercion can be implicit or explicit:

Implicit Coercion

Operations like addition, subtraction coerce integer to float implicitly (i.e. automatically), if one of the operands is float

1.0 + 2    # 3.0
1 + 2.0    # 3.0
1.0 + 2.0  # 3.0

1 + 2      # 3 (coercion not involved here)

Explicit Coercion

Built-in functions such as int(), float() and complex() are used to explicitly convert types.

int(2.3)        # 2
int(-2.8)       # -2
float(5)        # 5.0 
complex('3+5j') # (3+5j)

Python Decimal

Most divisions between floating numbers can't be stored accurately in our computer because of the binary representation of the fraction at the hardware level.

For example, this returns False, but mathematically speaking it is correct:

(1.1 + 2.2) == 3.3 # Python says False

To overcome this problem, the decimal module provided with Python can be used. While floating-point numbers have a precision of up to 15 decimal places, the decimal module has a user-settable precision.

import decimal

print(0.1)
print(decimal.Decimal(0.1))

Output

0.1
0.1000000000000000055511151231257827021181583404541015625

Also, it preserves decimal precision (i.e., the number of decimal places)

from decimal import Decimal as D

print(D('1.1') + D('2.2'))   # 3.3
print(D('1.2') * D('2.50'))  # 3.30

Python Fractions

Python provides operations involving fractional numbers through the fractions module.

  • A fraction has a numerator and a denominator, both of which are integers.
  • This module supports arithmetic of rational numbers.
import fractions

print(fractions.Fraction(1.5)) # 3/2
print(fractions.Fraction(5))   # 5
print(fractions.Fraction(1,3)) # 1/3

Fraction can be created starting from numbers or strings.

import fractions

print(fractions.Fraction(1.1))

print(fractions.Fraction('1.1'))

Fractions type supports all basic operations. A few examples:

from fractions import Fraction as F

print(F(1, 3) + F(1, 3))  # 2/3
print(1 / F(5, 6))        # 6/5
print(F(-3, 10) > 0)      # False
print(F(-3, 10) < 0)      # True

Python Mathematics

Python offers modules such as math and random to perform various mathematical operations such as trigonometry, logarithms, probability and statistics, etc.

math module

import math

print(math.pi)            # 3.141592653589793
print(math.cos(math.pi))  # -1.0
print(math.exp(10))       # 22026.465794806718
print(math.log10(1000))   # 3.0
print(math.sinh(1))       # 1.1752011936438014
print(math.factorial(6))  # 720

random module

import random

print(random.randrange(10, 20))

x = ['a', 'b', 'c', 'd', 'e']
print(random.choice(x)) # get random choice
random.shuffle(x)  # shuffle x
print(x)  # print the shuffled x
print(random.random())  # print random element

Operators

All operators that can be used on the numbers datatype are discussed on the Python Operators chapter.

Navigation