Python ROUND_HALF_UP not working as expected

后端 未结 1 1095
无人及你
无人及你 2021-01-18 11:49

I can\'t seem to understand the decimal docs to get 2.775 to round to 2.78 using the decimal class.

import decimal
decimal.getcontext().prec = 7
print(decima         


        
相关标签:
1条回答
  • 2021-01-18 12:13

    If you add a single line to your code thus:

    print (decimal.Decimal(2.775))
    

    then you'll see why it's rounding down:

    2.774999999999999911182158029987476766109466552734375
    

    The value 2.775, as a literal is stored as a double, which has limited precision.

    If you instead specify it as a string, the value will be preserved more accurately:

    >>> import decimal
    
    >>> print (decimal.Decimal(2.775))
    2.774999999999999911182158029987476766109466552734375
    
    >>> print (decimal.Decimal('2.775'))
    2.775
    
    0 讨论(0)
提交回复
热议问题