Python float() Function | Floating number, Float string python

This tutorial explains Python float() methodology that takes a quantity or string and returns a floating-point worth. If it is not in a position to convert string to float, then it raises the ValueError. Let’s try to know how one can use it with the assistance of easy examples.

1. float() syntax
2. float() with +ve numbers
3. float() with -ve numbers
4. float() with strings of numbers
5. float() with invalid inputs

Let’s now undergo every part one after the other.

Generate Float Range in Python

Python float() with Examples

Python Float() is a built-in Python performance that converts a quantity or a string to a float worth and returns the outcome. If it fails for any invalid entry, then an applicable exception happens.

Let’s now see the main points and try how can we use it.

Python Float() Syntax

The fundamental syntax to make use of Python float() is as follows:

float([ number or string])

Parameters:

First, the parameter is non-compulsory. If you don’t pass a price, then it returns 0.0. Also, the legitimate argument can solely be a quantity or a string containing some numeric worth.

You may know that Python assists advanced numbers such as 1+2j. But you possibly can’t pass it to the float() perform. However, you can provide each +ve and -ve numeric value.

Also, if you provide a string with a quantity with main or trailing areas, then it ignores the areas and returns a float worth.

Return Values:

The float() perform returns a floating-point worth equal to the quantity handed as is or in the type of a string.

Errors:

It raises the next exceptions when it receives invalid entered information.

ValueError – When you pass a mistaken argument such as a string that doesn’t include a quantity

TypeError – When you pass a sort argument that it doesn’t enable such as a fancy quantity or NoneSort

Python float() Examples:

Here, we’re utilizing float() to deal with totally different use circumstances. I Hope, these ought to allow you to this perform from all corners.

1. float() perform with +ve quantity values:

In this instance, we’ll pass +ve values in the float() name. So, it would merely convert them to an equal floating quantity.

"""
Desc:
Python instance to exhibit float() perform
"""

# Test Input
checkInput = [0, 1, 10000, 0.0, 1.1001, 1.000000000000001, 1.0000000000000001, 1.0000]

for everyItem in checkInput:
   print("float() = ".format(everyItem, float(everyItem)))

After executing the snippet proven above, you see the next outcome:

float(0) = 0.0
float(1) = 1.0
float(10000) = 10000.0
float(0.0) = 0.0
float(1.1001) = 1.1001
float(1.000000000000001) = 1.000000000000001
float(1.0) = 1.0
float(1.0) = 1.0
float(1.0) = 1.0

You can see that the floating #1.0000000000000001 obtained truncated to 1.0. It’s none apart from Python which is doing this. If you retail it to a variable, then even it reduces to 1.0.

2. float() perform with -ve numbers:

This time, we’ll execute float() on a gaggle of -ve values. We’ve saved all check numbers in an inventory to run our assessments.

"""
Desc:
Python instance to exhibit float() perform on -ve numbers
"""

# Test Input
checkInput = [-1, -10000, -0.0, -1.1001, -1.000000000000001, -1.0000000000000001, -1.0000]

for everyItem in checkInput:
   print("float() = ".format(everyItem, float(everyItem)))

This code would provide the following outcome:

float(-1) = -1.0
float(-10000) = -10000.0
float(-0.0) = -0.0
float(-1.1001) = -1.1001
float(-1.000000000000001) = -1.000000000000001
float(-1.0) = -1.0
float(-1.0) = -1.0

3. float() perform with a string containing numbers

When you pass a quantity in string format (in quotes), then float() converts the worth to float kind and returns the outcome.

For testing this, we’ve taken an inventory of strings containing each +ve and -ve number.

"""
Desc:
Python instance to exhibit float() perform on strings
"""

# Test Input
checkInput = ["-1", "-10000", "0.0", "1.1001", "1.000000000000001", "-1.0000000000000001", " 1.0000 "]

for everyItem in checkInput:
   print("float() = ".format(everyItem, float(everyItem)))

After working on this code, you’d get the next output:

float('-1') = -1.0
float('-10000') = -10000.0
float('0.0') = 0.0
float('1.1001') = 1.1001
float('1.000000000000001') = 1.000000000000001
float('-1.0000000000000001') = -1.0
float(' 1.0000 ') = 1.0

You can now undergo the outcome and perceive our check enter record including a number of values. And the float() performs efficiently and returned the right float values for every one of them. Also, it ignored the main and trailing areas as given in the last factor of the record.

Python float() perform additionally accepts phrases like NaN, Infinity, and inf (in decrease and higher circumstances). Let’s verify this reality with an instance.

"""
Desc:
Python float() exmaple for NaN, Infinity, inf
"""

# Test Input
checkInput = ["nan", "NaN", "inf", "InF", "InFiNiTy", "infinity"]

# Let's check float()
for everyItem in checkInput:
   if isinstance(everyItem, str):
      print("float('') = ".format(everyItem, float(everyItem)))
   else:
      print("float() = ".format(everyItem, float(everyItem)))

After working on the given code, the output is:

float('nan') = nan
float('NaN') = nan
float('inf') = inf
float('InF') = inf
float('InFiNiTy') = inf
float('infinity') = inf

float() perform with invalid inputs

Finally, we’ll check the float() perform by spending some invalid enter values. And hopefully, we’ll try to cowl all of the errors or exceptions it may throw.

Let’s see how float() functions with the mistaken parameters.

"""
Desc:
Python float() exmaple for invalid enter values
"""

# Test Input with all attainable invalid values
checkInput = [None, "Python", "0,1", "0 1", 1+2j]

# We'll use exception dealing with to continue even if some error happens
for everyItem in checkInput:
   try:
      if isinstance(everyItem, str):
         print("float('') = ".format(everyItem, float(everyItem)))
      else:
         print("float() = ".format(everyItem, float(everyItem)))
   except Exception as ex:
      print("float() = ".format(everyItem, ex))

# Also, verify for 1/0
try:
  print("float(1/0) = ".format(float(1/0)))
except Exception as ex:
  print("float(1/0) = ".format(ex))

Since this program raises exceptions for each invalid entry, therefore we used the Python try-except block to catch and print errors. After working on the given snippet, you see the next output:

float(None) = float() argument have to be a string or a quantity, not 'NoneSort'
float(Python) = might not convert string to float: 'Python'
float(0,1) = might not convert string to float: '0,1'
float(0 1) = might not convert string to float: '0 1'
float((1+2j)) = cannot convert advanced to float
float(1/0) = division by zero

We hope that after wrapping up this tutorial, you need to really feel comfy in utilizing the Python float() methodology. However, it’s possible you’ll observe more with examples to achieve confidence.

Also, to study Python from scratch to depth, do learn our step-by-step Python tutorial.

For more, refer to Wikipedia

Pramod Kumar Yadav is from Janakpur Dham, Nepal. He was born on December 23, 1994, and has one elder brother and two elder sisters. He completed his education at various schools and colleges in Nepal and completed a degree in Computer Science Engineering from MITS in Andhra Pradesh, India. Pramod has worked as the owner of RC Educational Foundation Pvt Ltd, a teacher, and an Educational Consultant, and is currently working as an Engineer and Digital Marketer.