简体   繁体   中英

Is there a more readable or Pythonic way to format a Decimal to 2 places?

What the heck is going on with the syntax to fix a Decimal to two places?

>>> from decimal import Decimal
>>> num = Decimal('1.0')
>>> num.quantize(Decimal(10) ** -2) # seriously?!
Decimal('1.00')

Is there a better way that doesn't look so esoteric at a glance? 'Quantizing a decimal' sounds like technobabble from an episode of Star Trek!

Use string formatting:

>>> from decimal import Decimal
>>> num = Decimal('1.0')
>>> format(num, '.2f')
'1.00'

The format() function applies string formatting to values. Decimal() objects can be formatted like floating point values.

You can also use this to interpolate the formatted decimal value is a larger string:

>>> 'Value of num: {:.2f}'.format(num)
'Value of num: 1.00'

See the format string syntax documentation .

Unless you know exactly what you are doing, expanding the number of significant digits through quantisation is not the way to go; quantisation is the privy of accountancy packages and normally has the aim to round results to fewer significant digits instead.

Quantize is used to set the number of places that are actually held internally within the value, before it is converted to a string. As Martijn points out this is usually done to reduce the number of digits via rounding, but it works just as well going the other way. By specifying the target as a decimal number rather than a number of places, you can make two values match without knowing specifically how many places are in them.

It looks a little less esoteric if you use a decimal value directly instead of trying to calculate it:

num.quantize(Decimal('0.01'))

You can set up some constants to hide the complexity:

places = [Decimal('0.1') ** n for n in range(16)]

num.quantize(places[2])

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