将Python小数对象格式化为指定的精度 [英] Format Python Decimal object to a specified precision

查看:118
本文介绍了将Python小数对象格式化为指定的精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了无数的时间进行研究,阅读,测试,最终对Python的Decimal对象缺乏最基本的概念感到困惑和沮丧:将Decimal的输出格式化为字符串。

I've spent countless hours researching, reading, testing, and ultimately confused and dismayed at Python's Decimal object's lack of the most fundamental concept: Formatting a Decimal's output to a string.

假设我们有一些具有以下值的字符串或十进制对象:

Let's assume we have some strings or Decimal objects with the following values:

   0.0008
  11.1111
 222.2222
3333.3333
1234.5678

目标是简单地设置小数位精度到小数点后两位。例如, 11.1111 的格式应为 11.11 1234.5678 1234.57

The goal is to simply set the Decimal's precision to the second decimal place. Eg, 11.1111 would be formatted as 11.11, and 1234.5678 as 1234.57.

我设想的代码类似于以下内容:

I envision code similar to the following:

import decimal
decimals = [
  decimal.Decimal('0.0008'),
  decimal.Decimal('11.1111'),
  decimal.Decimal('222.2222'),
  decimal.Decimal('3333.3333'),
  decimal.Decimal('1234.5678'),
]
for dec in decimals:
  print dec.as_string(precision=2, rounding=ROUND_HALF_UP)

结果输出将会是:

0.00
11.11
222.22
3333.33
1234.57

显然,我们不能利用Decimal的上下文精度,因为这考虑了TOTAL位数,而不是位数

Obviously we cannot make use of the Decimal's context's precision, because this takes into consideration the TOTAL number of digits, not just decimal precision.

我也不希望将Decimal转换为float以输出其值。十进制背后的全部原因是避免在浮点数上存储和运行计算。

I'm also not interested in converting the Decimal to a float to output its value. The ENTIRE reason behind Decimal is to avoid storing and running calculations on floats.

还有哪些其他解决方案?我知道在堆栈溢出时还有许多其他类似的问题,但是我没有发现它们可以解决我所查询的根本问题。

What other solutions are there? I understand there are many other similar questions on stack overflow, but none of them have I found to resolve the underlying issue I am inquiring of.

非常感谢!

推荐答案

只需使用字符串格式 format()函数

Just use string formatting or the format() function:

>>> for dec in decimals:
...    print format(dec, '7.2f')
... 
   0.00
  11.11
 222.22
3333.33
1234.57

decimal.Decimal 支持与浮点数相同的格式规范,所以您可以根据需要使用指数,定点,通用,数字或百分比格式。

decimal.Decimal supports the same format specifications as floats do, so you can use exponent, fixed point, general, number or percentage formatting as needed.

这是格式化小数的官方方法。 Decimal 类实现 .__ format __()方法来有效地处理这种格式。

This is the official and pythonic method of formatting decimals; the Decimal class implements the .__format__() method to handle such formatting efficiently.

这篇关于将Python小数对象格式化为指定的精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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