简体   繁体   中英

Printing a single Decimal produces a different output comparing to printing a list of Decimals

I've created a function that rounds half up, avoiding banker's rounding (ie 2.5 -> 3, not 2).

def rounding(n):
    context = decimal.getcontext()
    context.rounding = decimal.ROUND_HALF_UP
    value = round(decimal.Decimal(str(n)), 2)
    return value
print(rounding(0.245))

>>> 0.25

When I use it in a function, it works fine. But if the function returns 2 values or a list, it returns the Decimal function. See below.

def money(i, days):
    cash = i*days
    cash = rounding(cash)
    return cash
print(money(2.787, 5))

>>> 13.93

def money(i, days):
    cash = i*days
    cash = rounding(cash)
    return cash, cash
print(money(2.787, 5))

>>> (Decimal('13.93'), Decimal('13.93'))

def money(i, days):
    cash = i*days
    cash = rounding(cash)
    return [cash]
print(money(2.787, 5))

>>> [Decimal('13.93')]

Could someone explain what is happening here? Ultimately, I would like my result as:

>>> [13.93]

This is because print uses the __str__ representation of an object while if you're displaying a list it uses __repr__ for its elements. Compare the following example:

>>> d = decimal.Decimal('1.0')
>>> f'{d!r} vs. {d!s}'
"Decimal('1.0') vs. 1.0"

So if you're printing the Decimal directly, you're getting a float-like string representation while it's still the original Decimal object. Depending on what you want, you can convert the Decimal back using float(d) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM