PYTHON

Python Floats: Syntax, Usage, and Examples

A float, or floating-point number, is a data type in Python that represents real numbers with a decimal component.

How to Use Python Floats

A float in Python is created by including a decimal point in a number.

# Numbers with decimal points create floats
quarter = 0.25

Dividing two numbers results in a float, even if both numbers are integers.

# Generating a float by dividing two integers
third = 1 / 3  # Results in a float, approximately 0.3333

When to Use Python Floats

Floats are essential for working with floating-point numbers in Python. From simple arithmetic operations to more complex scientific calculations, floats are essential in almost every Python program.

Practical Examples of Working with Python Floats

Python programs of any kind use the float data type for improved precision over integers. Here are some simple examples:

Working with Decimals

The most basic use of floats is representing numbers with a decimal component as values or within variables.

inch_in_cm = 2.54

Calculating with Precision

Floats are essential for making calculations that require decimal precision. As an example, consider calculating the compound interest for investments or loans:

principal = 10000.0  # Initial amount
rate = 0.05  # Annual interest rate
time = 5  # Years
compound_interest = principal * ((1 + rate) ** time) - principal

Analyzing Data

Data science often involves handling floats for statistical calculations, data transformations, and visualizations.

import numpy as np

data = np.array([1.5, 2.3, 4.4, 5.9])
mean = np.mean(data)
print(f"Mean value: {mean:.2f}")

Learn More About Python Floats

Formatting Floats in Python

When displaying floats, showing a smaller number of decimal places might make a float easier to read. Using f-string formatting, you can control how many decimal places of a float you want to include. You can print floats in various formats, including percentages and scientific notation. Here are some common examples:

temperature = 23.56789
print(f"Temperature: {temperature:.1f}°C")  # Outputs: Temperature: 23.6°C

You can display a separator for thousands and two decimal places, for example when displaying financial information:

value = 2762.815625000003
print(f"Value: ${value:,.2f}")  # Outputs: Value: $2,762.82

You can also format floats as percentages, which is handy for displaying ratios or proportions.

progress = 0.853
print(f"Loading... {progress:.1%}")  # Outputs: Loading... 85.3%

For particularly large or small numbers, scientific notation provides a concise way to represent floats.

avogadros_number = 6.02214076e23
print(f"Avogadro's Number: {avogadros_number:.2e}")  # Outputs: Avogadro's Number: 6.02e+

When formatting floats for display, consider your context and audience. Financial data might require two decimal places. Scientific data, on the other hand, might need scientific notation or a specific number of significant figures.

Converting String to Float in Python

When processing user input or data from external sources, you can use the float() function to convert a Python string to a float. Once converted, the numbers are safe to use for calculations.

input_str = "123.45"
input_float = float(input_str)
print(input_float * 2)  # Outputs: 246.90

Converting Float to Int in Python

In some scenarios, you might need to convert floats to integers, either by truncation or rounding. In Python, float-to-int conversion is possible with the built-in int() function.

my_float = 7.75

# Truncating float to int
int_value = int(my_float)
print(int_value)  # Outputs: 7

# Rounding float and converting to int
rounded_int = round(my_float)
print(rounded_int)  # Outputs: 8

Rounding Floats

Sometimes, you might want to round float numbers to a certain number of decimal places. For this purpose, Python's built-in function round() is ideal:

import math
pi_approx = round(math.pi, 2)
print(f"Pi approximation: {pi_approx}")  # Outputs: Pi approximation: 3.14

Floating-Point Precision Issues

Unlike programming languages, computers represent floating-point numbers in binary. This can lead to precision errors because some decimal numbers are impossible to represent as binary fractions. For example, the decimal number 0.1 is not representable in a finite binary fraction. This leads to a small error when represented in binary.

Therefore, floating-point arithmetic can lead to precision issues and unexpected behavior. For example, checking for equality or summing up large amounts of data can be dangerous.

sum = 0.1 + 0.2
print(sum)  # Often outputs: 0.30000000000000004
print(sum == 0.3)  # Often outputs: False

For high-precision needs, particularly in financial applications, Python's decimal module provides operations for decimal arithmetic. This can prevent common floating-point issues, ensuring accuracy in calculations:

from decimal import Decimal

total = Decimal('0.1') + Decimal('0.2')
print(total == Decimal('0.3'))  # Outputs: True
Learn to Code in Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2024 Mimo GmbH