TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python Float() Explained
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

Python Float() Explained

Last updated: Oct 22, 2023 7:04 pm
By Meenakshi Agarwal
Share
8 Min Read
Python float() function with examples
Python float() function with examples
SHARE

This tutorial explains the Python float() method that takes a number or string and returns a floating-point value. If it is not able to convert the string to float, then it raises the ValueError. Let’s try to understand how to use it with the help of simple examples.

Contents
The float() SyntaxPython float() Examples1- Pass a mix of +ve regular and decimal numbers2- Pass the same set of numbers but with a -ve sign3- Testing float() with different strings of numbers4. Pass wrong values to the float() function

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 go through each of the sections one by one.

Also Check: Generate Float Range in Python

Python Float() Explained with Several Examples

Float() is a built-in Python function that converts a number or a string to a float value and returns the result. If it fails for any invalid input, then an appropriate exception occurs.

Let’s now see the details and check out how can we use it.

The float() Syntax

The basic syntax to use Python float() is as follows:

float([ A number or string])
ParameterDescription
x (required)The value or expression to convert into a floating-point number. It can be an integer, a string representing a floating-point number, or any valid numeric expression.
Parameter Info
Return ValueDescription
Floating-pointThe float() function returns the floating-point representation of the input value. If the input is already a floating-point number, it returns the same value. If the input is a string containing a valid floating-point representation, it converts and returns the equivalent floating-point number. If the input is a numeric expression, it calculates the result and returns it as a floating-point number.
Float() return value
Possible ErrorsDescription
ValueErrorIf the input x is not a valid numeric string or expression, the float() function raises a ValueError. For example, passing a string that contains non-numeric characters or an empty string would result in this error.
OverflowErrorIn rare cases, when attempting to convert extremely large or small numbers to float, an OverflowError might be raised. This occurs when the number is outside the range of representable floating-point values. It’s less common but still a possible error.
Errors thrown by Float()

Python float() Examples

Here, we are using float() to address different use cases. Hope, these should help you with this function from all corners.

1- Pass a mix of +ve regular and decimal numbers

In this example, we’ll provide a set of +ve values in the float() call. So, it should simply convert them to an equivalent floating-point number. Let’s see.

"""
Desc:
Python example to demonstrate float() function
"""

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

for eachItem in testInput:
   print("float({}) = {}".format(eachItem, float(eachItem)))

After executing the snippet shown above, you see the following result:

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 number 1.0000000000000001 got truncated to 1.0. It’s none other than Python which has rounded the float value. If you store it to a variable, then even it reduces to 1.0.

2- Pass the same set of numbers but with a -ve sign

This time, we’ll execute float() on a group of -ve values. We’ve stored all test numbers in a list to run our tests.

"""
Desc:
Python example to demonstrate float() function on -ve numbers
"""

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

for eachItem in testInput:
   print("float({}) = {}".format(eachItem, float(eachItem)))

This code would give you the following result:

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- Testing float() with different strings of numbers

When you send a number in text form, float() translates the value to Python float type.

To test this, we’ve taken a list of strings containing both +ve and -ve numbers.

"""
Desc:
Python example to demonstrate float() function on strings
"""

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

for eachItem in testInput:
   print("float({}) = {}".format(eachItem, float(eachItem)))

After running this code, you will get the following 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 go through the result and understand our test input list included multiple values. And, the float() function successfully returned the correct float values for each of them. Also, it removed the spaces from the start and end of the string as given in the last element of the list.

Python float() function also handles the following keywords both in lower and upper cases very well.

  • NaN,
  • Infinity,
  • Inf.

Let’s check this fact with an example.

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

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

# Let's test float()
for eachItem in testInput:
   if isinstance(eachItem, str):
      print('float ( "{}" ) => {}'.format(eachItem, float(eachItem)))
   else:
      print("float ( {} ) => {}".format(eachItem, float(eachItem)))

After running the given code, the output is:

float ( "nan" ) => nan
float ( "NaN" ) => nan
float ( "inf" ) => inf
float ( "InF" ) => inf
float ( "InFiNiTy" ) => inf
float ( "infinity" ) => inf

4. Pass wrong values to the float() function

Finally, we’ll test the Python float() function by passing the wrong parameters. And hopefully, we’ll try to cover all the errors or exceptions it can throw.

Let’s see how the float() function handles the wrong parameters.

# Description: Handling wrong values with the Python float() function

# Define a list of wrong values
wrong_values = [None, "Python", "0,1", "0 1", 1+2j]

# Initialize an index for iteration
index = 0

# Continue until the end of the list is reached
while index < len(wrong_values):
    wrong_value = wrong_values[index]
    try:
        # Attempt to convert to float; if it's not a string, this will raise a TypeError
        result = float(wrong_value)
        print(f"float({wrong_value}) = {result}")
    except ValueError as ex:
        if isinstance(wrong_value, str):
            print(f"float('{wrong_value}') = ValueError: {ex}")
        else:
            print(f"float({wrong_value}) = ValueError: {ex}")
    except TypeError as ex:
        print(f"float({wrong_value}) = TypeError: {ex}")
    
    # Increment the index for the next iteration
    index += 1

# Check for division by zero
try:
    result = float(1/0)
    print(f"float(1/0) = {result}")
except ZeroDivisionError as ex:
    print(f"float(1/0) = ZeroDivisionError: {ex}")
except ValueError as ex:
    print(f"float(1/0) = ValueError: {ex}")

Since this program raises exceptions for every invalid input, we used the Python try-except block to catch and print errors. After running the given snippet, you see the following output:

float(None) = TypeError: float() argument must be a string or a real number, not 'NoneType'
float('Python') = ValueError: could not convert string to float: 'Python'
float('0,1') = ValueError: could not convert string to float: '0,1'
float('0 1') = ValueError: could not convert string to float: '0 1'
float((1+2j)) = TypeError: float() argument must be a string or a real number, not 'complex'
float(1/0) = ZeroDivisionError: division by zero

We hope that after wrapping up this tutorial, you will feel comfortable using the Python float() method. However, you may practice more with examples to gain confidence.

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

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Python Check Integer Number in Range Python Check Integer Number in Range
Next Article MySQL UPPER() and UCASE() Functions Explained MySQL UPPER() and UCASE() Functions

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x