# Python float (Floating Point Number) Data Type

You are in Data Types

Tutorials:

This page is a summary of Python float (floating-point number or decimal number) data type – its basic characteristics, how to create a float variable, how to convert other data types to float, and basic arithmetic and comparison operations. It also explains the problem of floating point imprecision and typical situations when the float data type should not be used.

## Basic characteristics

Python `float` data type represents decimal numbers, such as `2.5`, `17.95`, `-0.0001`, or `0.0`.

A `float` can be positive, negative, or zero.

The main difference from the `int` (integer) data type is that a `float` can have digits after the decimal point, although they can be zeros. For instance, the number 5.0 can be a `float` (when typed as `5.0`) or an `int` (when typed as `5`).

`float` is short for floating-point number, which is a common way how computers represent real numbers. Its main advantage is performance – it allows storing a wide range of decimal numbers with a small amount of memory.

The performance benefits come at the cost of small imprecisions, due to the way decimal numbers are stored in the binary system. This problem is known as floating point imprecision and is not limited to Python. Typically, it only occurs several places after the decimal point and has no material effect in many use cases.

That said, Python has other data types to represent real numbers (such as `Decimal` or `Fraction`), which may be preferable to `float` when greater precision is required, such as in scientific or financial applications.

## How to create a float in Python

The simplest way to create an `float` variable is to assign a number to it, using the `=` assignment operator.

```a = 3.5
b = -3.5
c = 0.9```

If there are only zeros before or after the decimal point you don't need to type them.

```d = .125  # becomes the float 0.125
e = 125.  # becomes the float 125.0```

This is also how to create a whole number variable of the `float` type (such as `2.0`) – just add decimal point.

```x = 2  # becomes an int
y = 2.0  # becomes a float
z = 2.  # becomes a float```

If it has decimal point (even with only zeros after it or no digits at all), it becomes a `float`. If there is no decimal point, it becomes an `int`.

```>>> type(2.2)  # decimal number - float
<class 'float'>
>>> type(2)  # no decimal point - int
<class 'int'>
>>> type(2.0)  # decimal point, even with zero after - float
<class 'float'>
>>> type(2.)  # decimal point, even with no digits after - float
<class 'float'>```

## How to convert other data types to float

Some of the other Python data types can be converted to `float` using the built-in `float()` function.

### int to float

For example, this converts the `int` `108` to the `float` `-108.0`:

``a = float(108)``

Typing `float(108)` is equivalent to typing `108.` or `108.0` or `108.00000`.

Existing `int` variables (such as the variable named `some_int` below) can be converted to `float` in the same way:

```>>> some_int = 108
>>> type(some_int)
<class 'int'>
>>> converted_to_float = float(some_int)
>>> type(converted_to_float)
<class 'float'>```

### str to float

This converts the string `'-10.75'` to the `float` `-10.75`:

``a = float('-10.75')``

## Boolean evaluation of floats

When used in boolean context or evaluated with the `bool()` function, `float` works the same as `int`:

• Zero is `False`.
• Any other (positive or negative) numbers are `True`.
```>>> bool(0.0)
False
>>> bool(0.000000)
False
>>> bool(0.1)
True
>>> bool(-0.1)
True```

## Arithmetic operations with floats

Arithmetic operations with `float` work in the same way as with `int`:

• Addition: `a + b`
• Subtraction: `a - b`
• Multiplication: `a * b`
• Division: `a / b`
• Modulo (remainder): `a % b`
• Exponentiation: `a ** b`
```>>> 7.25 + 3.5
10.75
>>> 7.25 - 3.5
3.75
>>> 7.25 * 3.5
25.375
>>> 7.25 / 3.5
2.0714285714285716
>>> 7.25 % 3.5
0.25
>>> 7.25 ** 3.5
1026.0842537594017```

The result of these operations is always a `float`, as long as at least one of the inputs is a `float` (i.e. any operation between an `int` and a `float` returns a `float`).

The integer division operator (`//`) also works and returns the floor (whole number) as a `float`.

```>>> 7.25 // 3.5
2.0```

## Comparison operations with floats

Python supports all the common comparison operators between floats. They return a `bool` (`True`/`False`):

```>>> 7.25 > 3.5
True
>>> 7.25 < 3.5
False
>>> 7.25 >= 3.5
True
>>> 7.25 <= 3.5
False
>>> 7.25 == 3.5
False
>>> 7.25 != 3.5
True```

Comparison operators also work between floats and other numeric types, such as `int`:

```>>> 7.25 > 7
True
>>> 7.25 <= 7
False
>>> 7.0 == 7
True```

However, comparison operators do not work between floats and strings, even when the string represents a numeric value. We get a TypeError:

```>>> 7.25 < '8.25'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'float' and 'str'```

Be careful when comparing float variables. A variable supposed to be 12.00 may actually be something like 11.99999994375 or 12.00000001657, which may cause unexpected outcomes. This is known as floating-point imprecision and caused by the way decimal numbers are implemented as "floating-point numbers" in a computer's binary system of 0/1.

## What does a "floating-point number" mean?

The name float or floating-point number refers to the decimal point "floating" (having variable position) when such numbers are stored in computer memory.

Instead of storing a number all in one piece, the computer splits it into multiple parts: sign, significand (significant digits), and exponent (the power of 2 which decides where to put the decimal point).

It is similar to the more familiar scientific notation. For example, the number 0.00000875 is expressed as 8.75 * 10^-6, where the exponent -6 indicates the decimal point shifting 6 places to the left. This notation allows us to write very big or very small numbers with fewer digits.

While storing floating-point numbers in a computer's memory is a bit more complicated (using powers of 2, among other things), the main purpose is the same – to save digits (bits), so the number takes less space and can be processed faster.

## Floating point imprecision

The problem with storing decimal numbers (as floating-point numbers) in a computer's binary system is that most of them can't be really expressed precisely.

It is similar to the fractions like 2/3 being impossible to write in the decimal system, as you have an infinite sequence of sixes after the decimal point. Depending on your desired level of precision, you can write 2/3 as 0.67, 0.6667, or even 0.666666666667, but you have to do the rounding and write a 7 at some point.

For the same reason, the number 0.1 can't be expressed precisely in the binary system. Like 2/3 in decimal, it has an infinitely repeating sequence of digits in binary (0.00011001100110011...) and because a computer's memory is not infinte, it has to stop somewhere. As a result, when a computer is showing 0.1, it may as well be really meaning something like 0.09999990463 or 0.10000000149.

This imprecision can have serious consequences in programming. Rounding errors can accumulate and become bigger over time. Using `float` comparison operators for program logic (e.g. `if a == 0.1: ...`) may cause unexpected outcomes.

```>>> x = 0.1
>>> x * x
0.010000000000000002
>>> x ** 4 == x * x * x * x
False
>>> x ** 4
0.00010000000000000002
>>> x * x * x * x
0.00010000000000000003```

It is important to understand when the float data type is safe to use and when to use other (more precise yet less efficient) alternatives.

## When to use float data type and when not

Even with its imprecison problem, the `float` data type is widely used for its simplicity and performance. Because the imprecision typically occurs many places after the decimal point, it is not material in many use cases.

Exceptions when float should not be used are cases when greater precision is required or when there is a risk of small imprecisions accumulating over a large number of iterations. Common examples are the following:

Finance: If a financial application calculates compound interest with floats, a small imprecision in each calculation can lead to a large error over time, resulting in incorrect account balances or financial reports.

: In GPS systems, small rounding errors in the calculation of satellite positions can accumulate over time and result in a significant deviation from the actual position, leading to incorrect directions or even accidents.

Science: In a chemical reaction simulation, small imprecisions can accumulate over time and cause the reaction to proceed in unexpected ways, leading to inaccurate predictions of reaction rates and outcomes. This can have significant consequences in fields such as drug discovery and materials science.

Graphics: Floating point imprecision can cause artifacts such as "jitter" or "swimming" in rendered images. This can happen when the precision of the floating point numbers used to calculate vertex positions, lighting, and other effects is insufficient, leading to small variations in the position or appearance of objects that are noticeable to the viewer.

## More precise alternatives to float data type

When greater precision is required and the `float` data type is unsuitable, there are other Python modules and data types to work with real numbers:

`Decimal` – part of the `decimal` module, used for decimal numbers such as amounts of money
`Fraction` – part of the `fractions` module, used for rational numbers

## Official documentation

Numeric data types (`int`, `float`, `complex`):
https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex

The `float()` function:
https://docs.python.org/3/library/functions.html#float

Floating Point Arithmetic: Issues and Limitations
https://docs.python.org/3/tutorial/floatingpoint.html

By remaining on this website or using its content, you confirm that you have read and agree with the Terms of Use Agreement.

We are not liable for any damages resulting from using this website. Any information may be inaccurate or incomplete. See full Limitation of Liability.

Content may include affiliate links, which means we may earn commission if you buy on the linked website. See full Affiliate and Referral Disclosure.

We use cookies and similar technology to improve user experience and analyze traffic. See full Cookie Policy.