Is there a more readable or Pythonic way to format

2019-08-29 20:34发布

问题:

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!

回答1:

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.



回答2:

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])