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.

Syntax

The syntax of float() function is

float(x)

where

  • x is a string or a number, and is optional

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

Examples

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}')
Run

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}')
Run

Output

Float value : 3.14

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}')
Run

Output

Float value : 45.0

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}')
Run

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.