float() Builtin Function


Python - float()

Python float() builtin function takes a string or number, converts it into a floating point number, and returns the floating point number.

In this tutorial, you will learn the syntax of float() function, and then its usage with the help of example programs.

Syntax

The syntax of float() function is

float(x)

where

ParameterDescription
x[Optional] A string or a number.

If no argument is given to float(), then it returns zero.

Examples

1. Convert string to float

In the following program, we pass a string value to float() function. float() converts the given string into a floating point number.

Python Program

x = '3.14'
output = float(x)
print(f'Float value : {output}')

Output

Float value : 3.14

If the string has any leading or trailing spaces, then float() would first trim those spaces, and then parse the given string into a float.

Python Program

x = '  3.14 \n'
output = float(x)
print(f'Float value : {output}')

Output

Float value : 3.14

2. Convert integer to float

In the following program, we pass an integer value to float() function. float() converts the given integer into a floating point number.

Python Program

x = 45
output = float(x)
print(f'Float value : {output}')

Output

Float value : 45.0

3. float() with no argument

In the following program, we pass no argument to float() function. float() must return 0.0.

Python Program

output = float()
print(f'Float value : {output}')

Output

Float value : 0.0

Summary

In this tutorial of Python Examples, we learned the syntax of float() builtin function, and how to create a floating point number from string input or another numeric input, using float() function, with examples.