⬅ Previous Topic
Python filter() Function – Filter Items in a ListNext Topic ⮕
Python format() Function – Format Strings Easily⬅ Previous Topic
Python filter() Function – Filter Items in a ListNext Topic ⮕
Python format() Function – Format Strings Easilyfloat()
FunctionThe 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.
float([value])
value
(optional) – A number or a string that looks like a number.x = float(5)
print(x)
5.0
price = float("19.99")
print(price)
19.99
x = float()
print(x)
0.0
If no value is given, float()
returns 0.0
.
num = float("1e3")
print(num)
1000.0
float()
?float("hello") # ❌ Raises ValueError
0.1 + 0.2
may not be exactly 0.3
.In coding interviews, float()
is often used for type conversion before performing arithmetic or formatting results.
float()
converts int, str, or no argument to a decimal numberValueError
for invalid strings0.0
if called with no argumentsAsk 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)
⬅ Previous Topic
Python filter() Function – Filter Items in a ListNext Topic ⮕
Python format() Function – Format Strings EasilyYou 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.