我怎样才能把小数点的格式设定为小数点后两位呢?

时间:2022-09-17 11:15:00

I want to display:

我想要显示:

49 as 49.00

49为49.00

and:

和:

54.9 as 54.90

54.9至54.90

Regardless of the length of the decimal or whether there are are any decimal places, I would like to display a Decimal with 2 decimal places, and I'd like to do it in an efficient way. The purpose is to display money values.

不管小数点的长度是多少,或者是否有小数,我想要显示一个小数点后两位小数,我想用一种有效的方法。其目的是显示货币价值。

eg, 4898489.00

例如,4898489.00

8 个解决方案

#1


83  

I suppose you're probably using the Decimal() objects from the decimal module? (If you need exactly two digits of precision beyond the decimal point with arbitrarily large numbers, you definitely should be, and that's what your question's title suggests...)

我想你可能是在使用十进制模块中的十进制()对象?(如果你需要精确到小数点后两位的精确数字,你肯定应该是,这就是你的问题的题目所建议的…)

If so, the Decimal FAQ section of the docs has a question/answer pair which may be useful for you:

如果是这样,文档的小数FAQ部分有一个问题/答案对,可能对您有用:

Q. In a fixed-point application with two decimal places, some inputs have many places and need to be rounded. Others are not supposed to have excess digits and need to be validated. What methods should be used?

Q.在一个有两个小数点的定点应用程序中,一些输入有很多地方,需要四舍五入。其他人不应该有多余的数字,需要验证。应该使用什么方法?

A. The quantize() method rounds to a fixed number of decimal places. If the Inexact trap is set, it is also useful for validation:

方法的方法是:将方法的数量分配到一个固定的小数位数。如果设置了不精确的陷阱,它也可以用于验证:

>>> TWOPLACES = Decimal(10) ** -2       # same as Decimal('0.01')
>>> # Round to two places
>>> Decimal('3.214').quantize(TWOPLACES)
Decimal('3.21')
>>> # Validate that a number does not exceed two places
>>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Decimal('3.21')
>>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Traceback (most recent call last):
   ...
Inexact: None

The next question reads

下一个问题是

Q. Once I have valid two place inputs, how do I maintain that invariant throughout an application?

问:一旦我有了有效的两个位置输入,我如何在整个应用程序中保持不变?

If you need the answer to that (along with lots of other useful information), see the aforementioned section of the docs. Also, if you keep your Decimals with two digits of precision beyond the decimal point (meaning as much precision as is necessary to keep all digits to the left of the decimal point and two to the right of it and no more...), then converting them to strings with str will work fine:

如果您需要这个答案(以及许多其他有用的信息),请参见前面提到的文档部分。同样的,如果你保持你的两个数字的小数精度超出了小数点(意味着尽可能多的精度,有必要把所有数字的小数点左边和右边的两个,没有更多…),然后将它们转换为字符串str将正常工作:

str(Decimal('10'))
# -> '10'
str(Decimal('10.00'))
# -> '10.00'
str(Decimal('10.000'))
# -> '10.000'

#2


328  

You should use the new format specifications to define how your value should be represented:

您应该使用新的格式规范来定义您的值应该如何表示:

>>> from math import pi  # pi ~ 3.141592653589793
>>> '{0:.2f}'.format(pi)
'3.14'

The documentation can be a bit obtuse at times, so I recommend the following, easier readable references:

文档有时可能有点迟钝,所以我推荐以下更容易阅读的参考资料:

  • the Python String Format Cookbook: shows examples of the new-style .format() string formatting
  • Python字符串格式Cookbook:显示新样式.format()字符串格式的示例。
  • pyformat.info: compares the old-style % string formatting with the new-style .format() string formatting
  • info:比较旧式的% string格式和新式的.format()字符串格式。

Python 3.6 introduced literal string interpolation (also known as f-strings) so now you can write the above even more succinct as:

Python 3.6引入了文字字符串插值(也称为f-string),所以现在您可以将上面的内容写得更加简洁:

>>> f'{pi:.2f}'
'3.14'

#3


121  

The String Formatting Operations section of the Python documentation contains the answer you're looking for. In short:

Python文档的字符串格式化操作部分包含您正在寻找的答案。简而言之:

"%0.2f" % (num,)

Some examples:

一些例子:

>>> "%0.2f" % 10
'10.00'
>>> "%0.2f" % 1000
'1000.00'
>>> "%0.2f" % 10.1
'10.10'
>>> "%0.2f" % 10.120
'10.12'
>>> "%0.2f" % 10.126
'10.13'

#4


26  

You can use the string formatting operator as so:

您可以使用字符串格式化操作符:

num = 49
x = "%.2f" % num  # x is now the string "49.00"

I'm not sure what you mean by "efficient" -- this is almost certainly not the bottleneck of your application. If your program is running slowly, profile it first to find the hot spots, and then optimize those.

我不知道您说的“高效”是什么意思——这几乎肯定不是应用程序的瓶颈。如果你的程序运行缓慢,首先要对它进行配置,找出热点,然后对其进行优化。

#5


16  

.format is a more readable way to handle variable formatting:

.format是处理变量格式化的一种更可读的方式:

'{:.{prec}f}'.format(26.034, prec=2)

#6


15  

>>> print "{:.2f}".format(1.123456)
1.12

You can change 2 in 2f to any number of decimal points you want to show.

你可以把2f中的2换成任何你想要显示的小数点。

EDIT:

From Python3.6, this translates to:

从Python3.6,这转换为:

>>> print(f"{1.1234:.2f}")
1.12

#7


3  

if you have multiple parameters you can use

如果您有多个参数,您可以使用。

 print('some string {0:.2f} & {1:.2f}'.format(1.1234,2.345))
 >>> some string 1.12 & 2.35

#8


-3  

what about

是什么

print round(20.2564567 , 2)    >>>>>>>        20.25


print round(20.2564567 , 4)    >>>>>>>        20.2564

#1


83  

I suppose you're probably using the Decimal() objects from the decimal module? (If you need exactly two digits of precision beyond the decimal point with arbitrarily large numbers, you definitely should be, and that's what your question's title suggests...)

我想你可能是在使用十进制模块中的十进制()对象?(如果你需要精确到小数点后两位的精确数字,你肯定应该是,这就是你的问题的题目所建议的…)

If so, the Decimal FAQ section of the docs has a question/answer pair which may be useful for you:

如果是这样,文档的小数FAQ部分有一个问题/答案对,可能对您有用:

Q. In a fixed-point application with two decimal places, some inputs have many places and need to be rounded. Others are not supposed to have excess digits and need to be validated. What methods should be used?

Q.在一个有两个小数点的定点应用程序中,一些输入有很多地方,需要四舍五入。其他人不应该有多余的数字,需要验证。应该使用什么方法?

A. The quantize() method rounds to a fixed number of decimal places. If the Inexact trap is set, it is also useful for validation:

方法的方法是:将方法的数量分配到一个固定的小数位数。如果设置了不精确的陷阱,它也可以用于验证:

>>> TWOPLACES = Decimal(10) ** -2       # same as Decimal('0.01')
>>> # Round to two places
>>> Decimal('3.214').quantize(TWOPLACES)
Decimal('3.21')
>>> # Validate that a number does not exceed two places
>>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Decimal('3.21')
>>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Traceback (most recent call last):
   ...
Inexact: None

The next question reads

下一个问题是

Q. Once I have valid two place inputs, how do I maintain that invariant throughout an application?

问:一旦我有了有效的两个位置输入,我如何在整个应用程序中保持不变?

If you need the answer to that (along with lots of other useful information), see the aforementioned section of the docs. Also, if you keep your Decimals with two digits of precision beyond the decimal point (meaning as much precision as is necessary to keep all digits to the left of the decimal point and two to the right of it and no more...), then converting them to strings with str will work fine:

如果您需要这个答案(以及许多其他有用的信息),请参见前面提到的文档部分。同样的,如果你保持你的两个数字的小数精度超出了小数点(意味着尽可能多的精度,有必要把所有数字的小数点左边和右边的两个,没有更多…),然后将它们转换为字符串str将正常工作:

str(Decimal('10'))
# -> '10'
str(Decimal('10.00'))
# -> '10.00'
str(Decimal('10.000'))
# -> '10.000'

#2


328  

You should use the new format specifications to define how your value should be represented:

您应该使用新的格式规范来定义您的值应该如何表示:

>>> from math import pi  # pi ~ 3.141592653589793
>>> '{0:.2f}'.format(pi)
'3.14'

The documentation can be a bit obtuse at times, so I recommend the following, easier readable references:

文档有时可能有点迟钝,所以我推荐以下更容易阅读的参考资料:

  • the Python String Format Cookbook: shows examples of the new-style .format() string formatting
  • Python字符串格式Cookbook:显示新样式.format()字符串格式的示例。
  • pyformat.info: compares the old-style % string formatting with the new-style .format() string formatting
  • info:比较旧式的% string格式和新式的.format()字符串格式。

Python 3.6 introduced literal string interpolation (also known as f-strings) so now you can write the above even more succinct as:

Python 3.6引入了文字字符串插值(也称为f-string),所以现在您可以将上面的内容写得更加简洁:

>>> f'{pi:.2f}'
'3.14'

#3


121  

The String Formatting Operations section of the Python documentation contains the answer you're looking for. In short:

Python文档的字符串格式化操作部分包含您正在寻找的答案。简而言之:

"%0.2f" % (num,)

Some examples:

一些例子:

>>> "%0.2f" % 10
'10.00'
>>> "%0.2f" % 1000
'1000.00'
>>> "%0.2f" % 10.1
'10.10'
>>> "%0.2f" % 10.120
'10.12'
>>> "%0.2f" % 10.126
'10.13'

#4


26  

You can use the string formatting operator as so:

您可以使用字符串格式化操作符:

num = 49
x = "%.2f" % num  # x is now the string "49.00"

I'm not sure what you mean by "efficient" -- this is almost certainly not the bottleneck of your application. If your program is running slowly, profile it first to find the hot spots, and then optimize those.

我不知道您说的“高效”是什么意思——这几乎肯定不是应用程序的瓶颈。如果你的程序运行缓慢,首先要对它进行配置,找出热点,然后对其进行优化。

#5


16  

.format is a more readable way to handle variable formatting:

.format是处理变量格式化的一种更可读的方式:

'{:.{prec}f}'.format(26.034, prec=2)

#6


15  

>>> print "{:.2f}".format(1.123456)
1.12

You can change 2 in 2f to any number of decimal points you want to show.

你可以把2f中的2换成任何你想要显示的小数点。

EDIT:

From Python3.6, this translates to:

从Python3.6,这转换为:

>>> print(f"{1.1234:.2f}")
1.12

#7


3  

if you have multiple parameters you can use

如果您有多个参数,您可以使用。

 print('some string {0:.2f} & {1:.2f}'.format(1.1234,2.345))
 >>> some string 1.12 & 2.35

#8


-3  

what about

是什么

print round(20.2564567 , 2)    >>>>>>>        20.25


print round(20.2564567 , 4)    >>>>>>>        20.2564