Yandex

Python float() Function – Convert to Floating Point Number



Python float() Function

The float() function in Python is used to convert a number or a string into a floating-point number (i.e., a decimal number).

This is helpful when you need precision or decimal values in your calculations.

Syntax

float([value])

Parameters:

  • value (optional) – A number or a string that looks like a number.

Returns:

  • A floating-point number (decimal).

Example 1: Convert Integer to Float

x = float(5)
print(x)
5.0

Example 2: Convert String to Float

price = float("19.99")
print(price)
19.99

Example 3: Using float() Without Any Argument

x = float()
print(x)
0.0

If no value is given, float() returns 0.0.

Example 4: Convert Scientific Notation String

num = float("1e3")
print(num)
1000.0

Use Case: Why Use float()?

  • When reading decimal values from user input
  • For precise calculations (e.g., percentages, interest rates)
  • To convert values before arithmetic operations

Common Mistakes

  • Passing a non-numeric string:
  • float("hello")  # ❌ Raises ValueError
  • Expecting exact decimal representations: due to floating-point precision, results like 0.1 + 0.2 may not be exactly 0.3.

Interview Tip

In coding interviews, float() is often used for type conversion before performing arithmetic or formatting results.

Summary

  • float() converts int, str, or no argument to a decimal number
  • Raises ValueError for invalid strings
  • Returns 0.0 if called with no arguments

Practice Problem

Ask the user for a price and discount percentage, then calculate and print the final price.

price = float(input("Enter the price: "))
discount = float(input("Enter the discount %: "))
final_price = price - (price * discount / 100)
print("Final price after discount:", final_price)


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M