Hit enter after type your search item

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:


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:


Output:

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.


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:


The result:

True

False

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:


The output:

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

This div height required for enabling the sticky sidebar