Home  >  Article  >  Backend Development  >  How to solve the problem of number of digits after decimal point in Python

How to solve the problem of number of digits after decimal point in Python

王林
王林forward
2023-05-15 17:10:081645browse

    The number of digits after the decimal point in python

    The first method

    a = 8.8888

    Use the round function

    b = round(a,2) # 保留小数点后两位小数,会四舍五入
    b 就等于8.89

    th Two methods

    b= "%.2f"%a # 也会四舍五入

    The third method

    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)

    Python decimal point control

    Use python’s built-in round() function

    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:

    How to solve the problem of number of digits after decimal point in PythonUse the formatting method

    Special cases need to be noted the same as the round method

    How to solve the problem of number of digits after decimal point in Python

    Use the ceil and floor methods in the math module

    How to solve the problem of number of digits after decimal point in Python

    ceil(x) of the math module: take greater than or equal to The smallest integer of xHow to solve the problem of number of digits after decimal point in Python

    Floor(x) of the math module: Take the largest integer less than or equal to x
    • Precision analysis of more than 17 digits

    • Python's default is 17 digits of precision, which is 16 digits after the decimal point, but there is a problem here, that is, when our calculations need to use higher precision (more than 16 decimal places)?

    Use the decimal module with high precision and cooperate with getcontextHow to solve the problem of number of digits after decimal point in Python

    The default precision of the decimal module is 17 digits. You can modify the precision value by modifying getcontext().prec

    The 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!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete