In this tutorial we will learn about python float() method and ts uses.
What is python float() method?
The python float() method returns the floating-point number of a given number or a string; we can also use it for typecasting in python.
The syntax of float() is:
Python float() Parameters
The float() method takes only one parameter as an argument:
variable – a number or string that needs to be typecast to a floating-point number.
Let’s check an example of the float() method.
Example 1: How to use float() in python
The output will be as follows.
In the above program, we take multiple values like integer, string, string with whitespace, negative integer, and boolean. As you can see, we are using the float() method to convert them into a floating-point number. But when we use a boolean value, it will give 1.0 for True and 0.0 for False value.
We need to remember that it should be in numbers or Nan(not a number); otherwise, it will raise an error.
Example 2: How to use float() with string in python?
As you can see in the output, it converts all the strings with numbers but throws an error when using a string with PythonScholar because we cannot convert a string that is not a number.
Example 3: using float() with infinity and Nan(not a number)?
The output will be as follow:
Rules of float() method
- An argument must be an integer, string with a number, boolean, or Nan value.
- If the 0.0 value is passed, it will not return anything.
- It will cause an OverflowError exception when the argument is passed outside of the range of python float.