如何在 Python 中与小数相乘

在 Python 中与小数相乘

How to multiply with a Decimal in Python

与小数相乘:

  1. 使用模块中的Decimal()decimal获取十进制数。
  2. 使用乘法*运算符将小数乘以另一个数字。
  3. 可选择将结果四舍五入到 N 位精度。
主程序
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

第一个示例使用input()函数从用户输入中获取十进制数。

输入函数接受一个可选prompt参数并将其写入标准输出而没有尾随换行符

然后该函数从输入中读取该行,将其转换为字符串并返回结果。

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.

main.py
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.

The value we pass to the 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.

main.py
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.

main.py
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

round函数采用以下 2 个参数

姓名 描述
number 要舍入到ndigits小数点后精度的数字
ndigits 操作后数字应具有的小数点后的位数(可选)

round函数返回四舍五入到ndigits小数点后的精度的数字。

如果ndigits省略,函数返回最接近的整数。

主程序
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