Floating-point values and the float() method in Python
Floating-point values and the float() method in Python
Sep 15, 2022
Python Programming

In Python or any other programming languages, a float or, to be more exact, a floating point number is a type of data.

Programming languages, including Python, use various data type classification to store values. The type of data used will affect how a program can use the data and value. 

Within a program, the programmer can process the data in various ways: adding them, sorting them, subtracting them, and so on, and this data comes in various types. For example, your address is inputted as a string of characters.

With that being said, there are two different data types to store numerical values in Python: floats and integers. The main difference between the two is that floats can contain decimals, while integers cannot (whole numbers.)

When discussing floats in Python, we also have to differentiate between floats as a data type and the float() function or method, which is used to return a float number from strings and integers.

In this tutorial, we will discuss all you need to know about floats in Python and how you can use the float data type and float() method properly.

Float Data Type in Python

The float data type in Python represents the floating point numbers.

Most modern programming languages, including Python, recognize five basic categories of data types: Integral, Float, Character, Strings, and Composite.

  1. Integral: The Integral data type represents all whole numbers. Whole numbers are characterized by not having any fractional component (decimals).
  2. Characters: Alphabetic characters like 'a,' 'b,' and so on. Python, like many other modern programming languages, stores characters by representing each one using a small numeric code, typically as 8-bit unsigned integers from 0 to 255, mainly in ASCII code. In ASCII, the capital letter 'A' is represented by the number 65.
  3. Strings: Strings are collections of alphabetic characters like words and sentences. In Python, strings are arrays of Unicode characters.
  4. Composite: Composite data types refer to collections or groupings of multiple data types into a single entity. Array and list are examples of composite data types in Python.
  5. Float: Or Floating Point, represent all numbers that may have a fractional component or decimal. Float is used to represent real numbers with the decimal point dividing the integer (whole number) and fractional parts: 12.34, 12.3+e10, -12.34e21 are examples of floating point numbers.

Most modern programming languages, including Python, represent floating point numbers using the IEEE floating point standard as follows:

  1. One bit is used as a sign bit, which indicates the sign of the number.
  2. A specific number of bits are used to represent the numeric digits of the number, such as 602.
  3. The rest of the bits are used to indicate the position of the decimal point. -4, for example, can be used to yield the number 3.1234

Floating point data types can be differentiated by their precision. Precision is determined by the number of bits used to represent digits, which will also directly affect the total number of bits in the number: 

  • 32-bit single precision floats: use 32 total bits and 24 for a digit with about seven decimal places of precision ranging from 10^-38 to 10^38.
  • 64-bit double precision floats: use 64 total bits and 53 for a digit with about 16 decimal places of precision ranging from 10^-308 to 10^308. Often called doubles.
  • 128-bit quadruple precision floats: use 128 total bits and 113 for a digit with about 34 decimal places of precision ranging from 10^-4932 to 10^4932. Often called long doubles, quad doubles, or double-doubles.

Regardless of the precision, in programming and computer contexts, all floating point numbers should be considered as rounded-off approximations. 

For example, the decimal value 0.1 (or 1/10) cannot be represented as an exact floating-point number while using binary digits, as we've covered above.

In Python, float values are represented as 64-bit double-precision values. The maximum value a float number can have in Python is approx 1.8 x 10^308. Any number larger than this will be indicated by the string inf. 

For example, here is a sample Python code to demonstrate float values:

print(1.12e308)

print(1.88e308)

Output:

1.12e308

inf

Since 1.88 x10^308 is greater than 1.8 x 10^308, the compiler will print inf as the output.

Integers vs. Float in Python

In Python, any numerical value entered will be seen as a number by default, so it's not necessary to declare that a value is a number (as in other programming languages. 

With that being said, any numerical value entered into Python without decimals  (i.e., 12 or -12) will be interpreted as integers, and vice versa; any numerical value entered with decimals is interpreted as a float (i.e., 12.12 or -12.12.)

Integers in Python are commonly referred to using the term int, and Integers may include:

  • Positive whole numbers like 1, 2, 3, and so on
  • The number 0 without decimals
  • Negative whole numbers like -1, -2, -3, and so on

Floats, or floating point numbers in Python, on the other hand, are real numbers that can store decimal values. 

Both Integers and Floats are treated as numeric data types (numbers) in Python, so programmers can perform mathematical operations on them. 

Here is a simple program example of how to perform an additive mathematical operation involving floating point numbers: 

math_example = 12.3 + 45.6

print(math_example)

This code computes 12.3 + 45.6 and then returns 57.9.

Float() Method in Python

Python is an object-oriented language that deals with classes and objects to model the real world. 

In Python, a method is a function that is bound to a class that must be called on an object. You can refer to our tutorial for Python functions here to get a clearer picture of functions and methods in Python. 

The float() method is a built-in Python method that allows users and programmers to convert a string or an integer into a float data type.

In Python, the syntax for the float() method is:

float(value)

As you can see, the float() method only takes in one parameter, which is the value you want to convert to a float. The default value is 0.0.

This parameter is optional, and can be:

  • any whole number (integer)
  • any number in the form of a string (i.e., "12.3")
  • inf or NaN (any cases)

The float() method will return a floating point number value.

Values that can be returned by the Python float() method depend upon the argument passed as follows:

  • If no argument is passed 
  • If an argument is passed, the equivalent floating-point number is returned
  • Any string that is not a number with a decimal point can be passed but will return an error.
  • If a number is passed outside the range of Python float (as discussed above,) the code will return OverflowError

Converting a string to a float using the float() method

The string data type is a sequence of characters. 

In Python, the float() method can be used to convert any number in the form of a string to a floating-point number.

Here is an example of the application:

float_from_string = float("10")

print(float_from_string )

This code returns: 10.0.

In the above example, a numerical value (10) was stored as a string in the program. The float() method converted this value into a floating-point number, 10.0.

When necessary, programmers can use the + and - signs to denote whether you want your string to be converted to a positive floating number or a negative floating number. 

Here is an example of converting a string into a negative float:

float_from_string = float("-10")

print(float_from_string )

This code returns: -10.0.

In both examples above, the data is now stored as a float rather than a string. We can recognize this by observing whether the generated number is in quotation marks (signifying a string) and ends with. The . at the end tells us that the number previously stored as a string has been successfully converted to a floating-point number. 

Strings can also contain inf or infinity, representing infinity values (above 1.8 x 10^308), and NaN, representing invalid numbers. 

Converting a whole number integer to a float using the float() method

In Python, you can also use the float() method to convert a whole number integer into a float. 

Here is an example of such applications:

float_from_integer = float(10)

print(float_from_integer) 

This code returns: 10.0.

The code above used the float() method to convert an integer (10) into a floating-point number (10.0). As before, the . at the end of the returned output is a clear sign that the number has successfully been converted to a float.

Python Float() Method: More Applications and Examples

1. Code illustrating various examples of float()

 

# Python program to illustrate

# Various examples and applications of float()

 

# for integers

print(float(12.34))

 

# for floats

print(float(12))

 

# for strings

print(float("12"))

 

# for floating type strings

print(float("-12.34"))

 

# for string floats with whitespaces

print(float(" -23.45 \n"))

 

# for inf/infinity

print(float("InF"))

print(float("InFiNiTy"))

 

# for NaN

print(float("nan"))

print(float("NaN"))

 

# Error is generated at last

print(float("Test"))

 

This code will return the following output:

 

12.34

12.0

12.0

-12.34

-23.45

inf 

inf

nan

nan

All lines successfully passed the arguments and are executed properly. However, the last one will return an error:

Traceback (most recent call last):

  File "/home/21499f1e9ca207f0052f13d64cb6be31.py", line 25, in 

    print(float("Test"))

ValueError: could not convert string to float: 'Test'

2. Converting an integer to a floating point number in Python

# python code to convert integer

# float

integer= 10

output= float(integer)

print(output)

This code will return: 10.0.

3. Converting an integer to a floating point number in Python

# python code to convert string

# to float

string = "10"

output= float(string) 

print(output)

This code will return: 10.0.

4. Float() method for inf and nan

# Python program to illustrate

# Various examples and working of float()

 

# for inf/infinity

print(float("InF"))

print(float("InFiNiTy"))

 

# for NaN

print(float("nan"))

print(float("NaN"))

 

This code will return the following output:

inf

inf

nan

nan

5. Exception in Python float()

Float() will return ValueError if the passed argument is not a number or a numeric value stored as a string.

number = "test"

try:

    print(float(number))

except ValueError as e:

    print(e)

Output: 

could not convert string to float: 'test'

6. OverflowError in Float()

print(float(10**333))

Output:

Traceback (most recent call last):

  File "/home/1eb6a2abffa536ccb1cae660db04a162.py", line 1, in

    print(float(10**333))

OverflowError: int too large to convert to float

Float() will raise OverflowError if the passed argument is too large

Conclusion

Float as a data type (floating point numbers) is a crucial part of any modern programming language, including Python, allowing programmers to work with real numbers with decimal values.

In the tutorial above, we've discussed the basics of float data type in Python, as well as the differences between the floating-point number data type and other prominent data types like Integer and String. 

We have also discussed the float() method and how to use it to convert Integers and Strings into Floats, as well as real-life examples. 

You're now ready to start working with Float and the built-in Python float() method. However, if you need to learn more, 24HourAnswers.com has experienced Python tutors and more tutorials on Python and other programming languages, where you can learn and practice your knowledge more thoroughly.



View Available Computer Science Tutors