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

情到浓时终转凉″ 提交于 2019-12-12 06:45:16

问题


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


来源:https://stackoverflow.com/questions/18834897/is-there-a-more-readable-or-pythonic-way-to-format-a-decimal-to-2-places

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!