Home > Article > Backend Development > How to solve the problem of number of digits after decimal point in Python
a = 8.8888
Use the round function
b = round(a,2) # 保留小数点后两位小数,会四舍五入 b 就等于8.89
b= "%.2f"%a # 也会四舍五入
ret1 = Decimal("88.001").quantize(Decimal("0.00")) print(ret1) # 满5进1的写法 from decimal import Decimal, ROUND_HALF_UP res = Decimal(str(11.565)).quantize(Decimal("0.00"),ROUND_HALF_UP)
round()if There is only one number as a parameter, and when the number of digits is not specified, an integer is returned, and it is the closest integer.
Generally, the rounding rules are used, but the last digit of rounding is 5 If the number before the digit to be rounded is an even number, it will be discarded directly. If it is an odd number, it will be rounded upward. When the last digit entered is 5:
Use the formatting method
Special cases need to be noted the same as the round method
Use the ceil and floor methods in the math module
ceil(x) of the math module: take greater than or equal to The smallest integer of x
Floor(x) of the math module: Take the largest integer less than or equal to xPrecision analysis of more than 17 digits
Use the decimal module with high precision and cooperate with getcontext
The default precision of the decimal module is 17 digits. You can modify the precision value by modifying getcontext().precThe above is the detailed content of How to solve the problem of number of digits after decimal point in Python. For more information, please follow other related articles on the PHP Chinese website!