How To Use Float In Python

4 min read

Floating-point numbers are everywhere in Python: prices, measurements, scientific calculations, percentages, and even simple averages. Understanding how to use float in Python is one of the first real skills that separates beginners from confident programmers, because floats behave differently from integers in ways that can quietly break your code. This guide walks you through creating floats, converting between types, formatting output, handling rounding, avoiding precision traps, and writing comparisons that actually work Still holds up..

What Is a Float in Python?

A float (short for floating-point number) is Python's data type for representing real numbers with a decimal point or an exponent. 5, or 2.14, -0.Unlike integers, floats can store fractional values such as 3.5e3 Simple, but easy to overlook..

Internally, Python stores floats using IEEE 754 double precision, which means each float occupies 64 bits and offers roughly 15–17 significant decimal digits of accuracy. That design gives you a huge range of values, but it also introduces the famous rounding quirks you will meet later in this article.

price = 19.99
temperature = -3.5
scientific = 6.02e23
print(type(price))  # 

How to Create Float Values in Python

There are several natural ways to produce a float.

1. Write a literal with a decimal point

Any number containing a decimal point or an exponent is automatically a float.

a = 3.0
b = 0.001
c = 1.5e-4   # 0.00015

2. Use the float() constructor

The built-in float() function converts strings, integers, and other compatible objects into floats.

float("42.75")   # 42.75
float(7)         # 7.0
float("-1e3")    # -1000.0
float(True)      # 1.0

3. Get a float from division

In Python 3, the / operator always returns a float, even when both operands are integers.

print(10 / 2)    # 5.0
print(7 / 3)     # 2.3333333333333335

Use // if you want floor division that keeps an integer result Simple, but easy to overlook..

4. Convert with arithmetic

Mixing a float with an integer in any arithmetic operation promotes the result to a float Worth keeping that in mind..

result = 5 * 2.0   # 10.0

Converting Between Floats and Other Types

Conversion is a daily task, especially when reading user input or data files That's the whole idea..

Conversion Method Example
String → float float() float("3.On top of that, 14
Integer → float float() float(9) → 9. Worth adding: 0
Float → integer int() int(3. 99) → 3 (truncates)
Float → string str() str(2.14") → 3.5) → "2.5"
Float → rounded int round() `round(3.

A common real-world pattern is validating user input:

raw = input("Enter a price: ")
try:
    price = float(raw)
    print(f"Price with tax: {price * 1.11:.2f}")
except ValueError:
    print("That is not a valid number.")

Always wrap float() conversions in a try/except block when the source is untrusted, because invalid strings raise a ValueError.

Formatting Floats for Display

Raw floats often print with long tails like 2.3333333333333335. Use f-strings to control how many decimals appear.

value = 2.34567
print(f"{value:.2f}")    # 2.35
print(f"{value:.4f}")    # 2.3457
print(f"{value:10.2f}")  # right-aligned in 10 spaces
print(f"{value:.1%}")    # 234.6%

You can also use round() when you need a numeric result rather than a formatted string:

round(2.675, 2)   # 2.67 — surprising, see the precision section

The Precision Problem Every Python Developer Meets

Try this in your interpreter:

print(0.1 + 0.2)   # 0.30000000000000004
print(0.1 + 0.2 == 0.3)  # False

This is not a Python bug. Because floats are stored in binary, many decimal fractions cannot be represented exactly, just as 1/3 cannot be written exactly in decimal. The tiny error is invisible in most applications but becomes critical in financial calculations or equality checks Not complicated — just consistent..

Not obvious, but once you see it — you'll see it everywhere.

Solutions for precision issues

  • Use round() for display-level fixes: round(0.1 + 0.2, 2) == 0.3.
  • Use the decimal module for money and exact decimal arithmetic.
  • Use math.isclose() instead of == when comparing floats.
  • Use fractions.Fraction when you need exact rational values.
from decimal import Decimal
print(Decimal("0.1") + Decimal("0.2"))   # 0.3

import math
print(math.isclose(0.1 + 0.2, 0.3))      # True

Comparing Floats Safely

Never rely on == for computed floats. Instead, check whether two values are close within a tolerance.

import math

a = 0.1 + 0.2
b = 0.3

print(a == b)                      # False
print(math.isclose(a, b))          # True
print(math.isclose(a, b, rel_tol=1e-9, abs_tol=1e-12))

math.isclose() accepts a relative tolerance (rel_tol) and an absolute tolerance (abs_tol), letting you tune the comparison to your domain.

Special Float Values: Infinity and NaN

Python floats support three special values you should recognize:

  • float('inf') — positive infinity
  • float('-inf') — negative infinity
  • float('nan') — "not a number"
import math

x = float('inf')
print(x > 10**100)        # True
print(math.isinf(x))      # True

n = float('nan')
print(n == n)             # False — NaN is never equal to itself
print(math.isnan(n))      # True

Because NaN never equals itself, always test it with math.isnan() rather than ==.

Practical Float Operations You Will Use Often

Arithmetic and math functions

import math

print(abs(-4.5))          # 4.5
print(math.Still, sqrt(2))       # 1. On top of that, 4142135623730951
print(math. Here's the thing — floor(3. 9))    # 3
print(math.Practically speaking, ceil(3. Worth adding: 1))     # 4
print(divmod(7. Consider this: 5, 2))     # (3. 0, 1.

### Averaging a list of numbers

```python
scores = [88.5, 92.0, 79.25, 95.75]
average = sum(scores) / len(scores)
print(f"Average: {
Don't Stop

Recently Launched

A Natural Continuation

Round It Out With These

Thank you for reading about How To Use Float In Python. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home