有没有更易读或Python的方式将小数点格式设置为2个位? [英] Is there a more readable or Pythonic way to format a Decimal to 2 places?

查看:60
本文介绍了有没有更易读或Python的方式将小数点格式设置为2个位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将小数点固定到两个位置的语法到底是怎么回事?

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!

推荐答案

使用字符串格式:

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

format()函数适用字符串格式化为值。 Decimal()对象的格式可以像浮点值一样。

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'

请参见格式字符串语法文档

除非您确切地知道自己在做什么,否则通过量化来扩展有效位数的方法是行不通的。量化是会计软件包的不足之处,通常旨在将结果舍入到更少个有效数字。

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.

这篇关于有没有更易读或Python的方式将小数点格式设置为2个位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆