What is float function in Python?

The Python float function converts a given value into the float. The float function takes an argument that can be a number or string with the decimal point. For example:

flt_num = float(10)

flt_str = float(“10.5”)

Syntax of using float function

class float([x])

Where x argument rules are as follows:

  • If x is a string then it should be a decimal number.
  • For a string, you may optionally use a ‘+’ or ‘–‘ sign. Using the ‘+’ sign does not affect the result.
  • If x is a string and contains leading or trailing spaces, these are removed.
  • A string representing NaN (not-a-number) may also be used.
  • An int or float number can be used as an argument. In that case, the floating point number with the same value is returned.

An example of converting a string to float

In the example below, we have a decimal number as a string that is used as an argument in the float Python function. The code and result are shown below:

#Python float demos

flt_x = float("43.59")

print("The returned float number:" ,flt_x)

The result:

The returned float number: 43.59

Using leading and trailing spaces in string example

Now,  I used leading and trailing spaces with a decimal number in the string. As mentioned earlier, the spaces should be removed by float function. See the code and output below:

#Python float demos

str_num = "   55.48   "

flt_spaces = float(str_num)

print("Original string:" ,str_num)

print("After float function:" ,flt_spaces)


Python float

You see, the original string shows spaces while as I displayed the value after using float function, the spaces in left and right are removed.

The example of using int and float

This example shows the returned values after using an int and floating numbers in the float function.

int_num = 35

flt_num = 61.89

print("Int after float function:" ,float(int_num))

print("Float number after:" ,float(flt_num))

The output:

Int after float function: 35.0

Float number after: 61.89

An example of checking if a value is NaN

The example below uses math module and checks if the value is NaN by float function:

import math

print (math.isnan(float('NaN')))

print (math.isnan(25.0))

The result:



What if an alphabet is used in float function?

A ValueError will be generated if alphabets are given in the float function. Have a look at an example below:

str_flt = "test"

print (float(str_flt))

The output:

ValueError: could not convert string to float: ‘test’

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!