When working with decimal numbers in Python, it’s necessary to know how to perform basic operations such as addition, subtraction, multiplication, and division.
In this tutorial, you’ll learn how to multiply decimal numbers specifically in Python using the decimal module which offers greater precision and control when dealing with floating-point numbers as compared to the default floating-point behavior.
Step 1: Import the decimal module
First, you need to import the decimal module provided by Python. It contains the Decimal class that you’ll use to perform multiplications on decimal numbers. To import the decimal module, simply type the following line of code:
1 |
import decimal |
Step 2: Define your decimal numbers
Once the module is imported, you can create Decimal instances representing the numbers you want to multiply. Make sure you define them as a string, otherwise the module might not use the exact value you intended. For example, to define the decimal numbers 3.65 and 12.00, you can write:
1 2 |
number1 = decimal.Decimal('3.65') number2 = decimal.Decimal('12.00') |
Step 3: Multiply the decimal numbers
Now that you’ve defined your decimal numbers as Decimal instances, you can multiply them using the asterisk (*) operator. The resulting product will also be a Decimal instance. Here’s how to do it:
1 |
product = number1 * number2 |
Step 4: Convert the result to a string or float (optional)
After obtaining the product, you may want to convert it to a string or float to make it easier to work with or display in your program. To convert the result to a string, use the str() function:
1 |
product_string = str(product) |
And to convert the result to a float, use the float() function:
1 |
product_float = float(product) |
Step 5: Display the result
Finally, you can print the result of the multiplication to see the output. Just use the print() function to display the product:
1 |
print("The product of", number1, "and", number2, "is", product) |
This will display the following output:
The product of 3.65 and 12.00 is 43.8000
Conclusion
And that’s it! You’ve just learned how to multiply decimals in Python using the decimal module. Remember that this module offers better precision than the default floating-point behavior, making it more suitable for calculations that require exact values.
Here’s the full code for your reference:
1 2 3 4 5 6 7 8 |
import decimal number1 = decimal.Decimal('3.65') number2 = decimal.Decimal('12.00') product = number1 * number2 print("The product of", number1, "and", number2, "is", product) |