如何将Python十进制数舍入到2位小数? [英] How to round a Python Decimal to 2 decimal places?

查看:228
本文介绍了如何将Python十进制数舍入到2位小数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python十进制(货币数量),我想四舍五入到小数点后两位。我试着用正则round()函数来做这个。不幸的是,这将返回一个浮点数,这使得它不可靠继续:

 >>> from decimal import Decimal 
>>> a =十进制('1.23456789')
>>>类型(round(a,2))

在小数模块中,我看到了一些与舍入有关的事情:




  • ROUND_05UP

  • ROUND_CEILING

  • ROUND_DOWN li> ROUND_FLOOR

  • ROUND_HALF_DOWN

  • ROUND_HALF_EVEN
  • ROUND_HALF_UP
  • ROUND_UP
  • Rounded



我认为这些实际上没有给我想要的东西(或我的错误在这里?)。

所以我的问题:是否有人知道我如何可靠地将Python十进制数舍入到2位小数,以便我有一个十进制数继续?所有的提示都是值得欢迎的! /library/decimal.html#decimal.Decimal.quantize> quantize() method :

 >>>进口十进制
>>> decimal.getcontext()。prec = 20
>>> a = decimal.Decimal(321.12345)
>>> a
十进制('321.12344999999999117790139280259609222412109375')
>>> TWO_PLACES = decimal.Decimal(0.01)
>>> a.quantize(TWO_PLACES)
十进制('321.12')


I've got a python Decimal (a currency amount) which I want to round to two decimal places. I tried doing this using the regular round() function. Unfortunately, this returns a float, which makes it unreliable to continue with:

>>> from decimal import Decimal
>>> a = Decimal('1.23456789')
>>> type(round(a, 2))
<type 'float'>

in the decimal module, I see a couple things in relation to rounding:

  • ROUND_05UP
  • ROUND_CEILING
  • ROUND_DOWN
  • ROUND_FLOOR
  • ROUND_HALF_DOWN
  • ROUND_HALF_EVEN
  • ROUND_HALF_UP
  • ROUND_UP
  • Rounded

I think that none of these actually give what I want though (or am I wrong here?).

So my question: does anybody know how I can reliably round a Python Decimal to 2 decimal places so that I have a Decimal to continue with? All tips are welcome!

解决方案

You could use the quantize() method:

>>> import decimal
>>> decimal.getcontext().prec = 20
>>> a = decimal.Decimal(321.12345)
>>> a
Decimal('321.12344999999999117790139280259609222412109375')
>>> TWO_PLACES = decimal.Decimal("0.01")
>>> a.quantize(TWO_PLACES)
Decimal('321.12')

这篇关于如何将Python十进制数舍入到2位小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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