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


Python float() Function|Floating quantity, 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 of the part one after the other.

Generate Float Range in Python

Python float() with Examples

Python Float() is a built-in Python perform that converts a quantity or a string to a float worth and returns the outcome. If it fails for any invalid enter, 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 assist 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 values.

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 enter 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. 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 the Python which is doing this. If you retailer 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 numbers.

"""
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 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 included a number of values. And the float() perform efficiently returned the right float values for every 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, 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 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 exception it may throw.

Let’s see how does float() function 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 enter, therefore we used Python try-except block to catch and print errors. After working 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 Search in Wikipedia

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

Categories

You have successfully subscribed to myprogrammingschool

There was an error while trying to send your request. Please try again.

My Programming School will use the information you provide on this form to be in touch with you and to provide updates and marketing.