Borislav Hadzhiev
Last updated: Jul 9, 2022
Photo from Unsplash
To multiply with a decimal:
Decimal()
class from the decimal
module to get a decimal number.*
operator to multiply the decimal by another
number.from decimal import Decimal decimal_1 = input('Enter your favorite decimal: ') print(decimal_1) # 👉️ '.4' my_int = 3 # 👇️ convert string to decimal result = Decimal(decimal_1) * my_int print(result) # 👉️ 1.2 # -------------------------------- decimal_2 = Decimal(3.14) result_2 = decimal_2 * 4 print(result_2) # 👉️ 12.56000... # 👇️ use round() to round to N digits precision print(round(result_2, 2)) # 👉️ 12.56
The first example uses the input()
function to get a decimal number from user
input.
The input function
takes an optional prompt
argument and writes it to standard output without a
trailing newline.
Note that the input()
function always returns a string, even if the user
enters a number.
You can pass the string to the Decimal()
class to convert it to a decimal.
from decimal import Decimal decimal_1 = input('Enter your favorite decimal: ') print(decimal_1) # 👉️ '.4' my_int = 3 # 👇️ convert string to decimal result = Decimal(decimal_1) * my_int print(result) # 👉️ 1.2
The decimal.Decimal class constructs a new Decimal object from a value.
decimal.Decimal
class can be an integer, string, tuple, float, or another Decimal
object.If you call the Decimal
class without passing a value, it returns 0
.
If the user enters a value that is not a valid decimal number, a
decimal.InvalidOperation
error is raised.
You can use a try/except
block if you need to handle the error.
from decimal import Decimal, InvalidOperation decimal_1 = input('Enter your favorite decimal: ') print(decimal_1) # 👉️ '.4' my_int = 3 try: result = Decimal(decimal_1) * my_int print(result) # 👉️ 1.2 except InvalidOperation: print('Value cannot be converted to decimal')
If you need to round the multiplication result to N digits precision, use the
round()
function.
from decimal import Decimal decimal_2 = Decimal(3.14) result_2 = decimal_2 * 4 print(result_2) # 👉️ 12.56000... # 👇️ use round() to round to N digits precision print(round(result_2, 2)) # 👉️ 12.56
The round function takes the following 2 parameters:
Name | Description |
---|---|
number | the number to round to ndigits precision after the decimal |
ndigits | the number of digits after the decimal the number should have after the operation (optional) |
The round
function returns the number rounded to ndigits
precision after the
decimal point.
If ndigits
is omitted, the function returns the nearest integer.
from decimal import Decimal fav_num = Decimal(3.456) result1 = round(fav_num) print(result1) # 👉️ 3 result2 = round(fav_num, 2) print(result2) # 👉️ 3.46