简体   繁体   English

有没有更易读或Python的方式将小数点格式设置为2个位?

[英]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. format()函数将字符串格式应用于值。 Decimal() objects can be formatted like floating point values. Decimal()对象的格式可以像浮点值一样。

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. Quantize用于设置在值内部实际保留的位数,然后再将其转换为字符串。 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. 正如Martijn所指出的那样,通常这样做是为了通过舍入来减少位数,但是反之亦然。 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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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