`
xiao80xiao
  • 浏览: 80383 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

python Decimal 使用

阅读更多

地址:http://docs.python.org/library/decimal.html

 

Decimal支持大多数的数学操作。使用decimal的时候是在一个context背景下工作的。可以使用getcontext来获得当前背景:

 

from decimal import *

c = getcontext()

print c

 

结果:

 

Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, capitals=1, flags=[], traps=[Overflow, InvalidOperation, DivisionByZero])

 

使用Decimal,int类型可以直接用来构造Decimal,但是float类型的变量要先转换为字符串。在进行运算之后结果会使用getcontext().prec来确定精度,例如prec为5的时候,100.1234567890+0会等于100.12:

 

# -*- coding: cp936 -*-

from decimal import *

con = getcontext()

print '-----------------------context------------------------'

print con

a = Decimal(100)

print a

b = Decimal('100.001')

print b

print '--------------------------prec------------------------------'

c = Decimal('100.1234567890')

print c

con.prec = 5

print con

d = Decimal('100.1234567890')

print 'd:',d

print 'd+0:',d+0

 

结果:

 

>>>

-----------------------context------------------------

Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, capitals=1, flags=[], traps=[DivisionByZero, InvalidOperation, Overflow])

100

100.001

--------------------------prec------------------------------

100.1234567890

Context(prec=5, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, capitals=1, flags=[], traps=[DivisionByZero, InvalidOperation, Overflow])

d: 100.1234567890

d+0: 100.12

 

可以修改Context来改变Decimal运算的行为,例如精度、如何舍弃位数等等。例如下面的程序测试各种rounding设置对结果的影响:

 

# -*- coding: cp936 -*-

from decimal import *

con = getcontext()

con.prec = 5

print '-----------------------context------------------------'

print con

s = '100.005'

strs = [

    '100.005',

    '100.004',

    '-100.005',

    '-100.004',

    ]

round_methods = [

    ROUND_CEILING,

    ROUND_DOWN,

    ROUND_FLOOR,

    ROUND_HALF_DOWN,

    ROUND_HALF_EVEN,

    ROUND_HALF_UP,

    ROUND_UP,

    ROUND_05UP,

    ]

for method in round_methods:

    con.rounding = method

    print '----------------------------', con.rounding, '----------------------------'

    for s in strs:

        print ' %s+0:' % s, Decimal(s)+0

 

结果:

 

>>>

-----------------------context------------------------

Context(prec=5, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, capitals=1, flags=[], traps=[DivisionByZero, Overflow, InvalidOperation])

---------------------------- ROUND_CEILING ----------------------------

 100.005+0: 100.01

 100.004+0: 100.01

 -100.005+0: -100.00

 -100.004+0: -100.00

---------------------------- ROUND_DOWN ----------------------------

 100.005+0: 100.00

 100.004+0: 100.00

 -100.005+0: -100.00

 -100.004+0: -100.00

---------------------------- ROUND_FLOOR ----------------------------

 100.005+0: 100.00

 100.004+0: 100.00

 -100.005+0: -100.01

 -100.004+0: -100.01

---------------------------- ROUND_HALF_DOWN ----------------------------

 100.005+0: 100.00

 100.004+0: 100.00

 -100.005+0: -100.00

 -100.004+0: -100.00

---------------------------- ROUND_HALF_EVEN ----------------------------

 100.005+0: 100.00

 100.004+0: 100.00

 -100.005+0: -100.00

 -100.004+0: -100.00

---------------------------- ROUND_HALF_UP ----------------------------

 100.005+0: 100.01

 100.004+0: 100.00

 -100.005+0: -100.01

 -100.004+0: -100.00

---------------------------- ROUND_UP ----------------------------

 100.005+0: 100.01

 100.004+0: 100.01

 -100.005+0: -100.01

 -100.004+0: -100.01

---------------------------- ROUND_05UP ----------------------------

 100.005+0: 100.01

 100.004+0: 100.01

 -100.005+0: -100.01

 -100.004+0: -100.01

>>>

 

文档里有一个将Decimal转换为现金格式的函数:

 

def moneyfmt(value, places=2, curr='', sep=',', dp='.',

             pos='', neg='-', trailneg=''):

    """Convert Decimal to a money formatted string.

 

    places:  required number of places after the decimal point

    curr:    optional currency symbol before the sign (may be blank)

    sep:     optional grouping separator (comma, period, space, or blank)

    dp:      decimal point indicator (comma or period)

             only specify as blank when places is zero

    pos:     optional sign for positive numbers: '+', space or blank

    neg:     optional sign for negative numbers: '-', '(', space or blank

    trailneg:optional trailing minus indicator:  '-', ')', space or blank

 

    >>> d = Decimal('-1234567.8901')

    >>> moneyfmt(d, curr='$')

    '-$1,234,567.89'

    >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')

    '1.234.568-'

    >>> moneyfmt(d, curr='$', neg='(', trailneg=')')

    '($1,234,567.89)'

    >>> moneyfmt(Decimal(123456789), sep=' ')

    '123 456 789.00'

    >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')

    '<0.02>'

 

    """

    q = Decimal(10) ** -places      # 2 places --> '0.01'

    sign, digits, exp = value.quantize(q).as_tuple()

    result = []

    digits = map(str, digits)

    build, next = result.append, digits.pop

    if sign:

        build(trailneg)

    for i in range(places):

        build(next() if digits else '0')

    build(dp)

    if not digits:

        build('0')

    i = 0

    while digits:

        build(next())

        i += 1

        if i == 3 and digits:

            i = 0

            build(sep)

    build(curr)

    build(neg if sign else pos)

    return ''.join(reversed(result))

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/runningtortoise/archive/2009/07/19/4361494.aspx

 

分享到:
评论

相关推荐

    python中的decimal类型转换实例详解

    decimal 模块实现了定点和浮点算术运算符,使用的是大多数人所熟悉的模型,而不是程序员熟悉的模型,即大多数计算机硬件实现的 IEEE 浮点数运算。这篇文章主要介绍了python里的decimal类型转换,需要的朋友可以参考下

    Python decimal模块使用方法详解

    主要介绍了Python decimal模块使用方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

    实例详解Python模块decimal

    主要介绍了Python模块decimal ,Python提供了decimal模块用于十进制数学计算,它具有以下特点在文中给大家详细介绍,需要的朋友可以参考下

    Decimal性能测试报告1

    3.2 decimal数据类型的引入对double数据类型插入速度的影响 3.3 decimal数据类型的引入有无导致内存泄漏 3.4 与旧版decimal的对

    Decimal scaling标准化的python代码

    Decimal scaling标准化的python代码

    python 3.5.2官方API

    HTML格式

    转换科学计数法的数值字符串为decimal类型的方法

    在操作数据库时,需要将字符串转换成decimal类型。 代码如下: select cast('0.12' as decimal(18,2)); select convert(decimal(18,2), '0.12'); 当需要将科学计数法的数字字符串转换成decimal时,这2种写法都...

    python3.6.5参考手册 chm

    Python参考手册,官方正式版参考手册,chm版。以下摘取部分内容:Navigation index modules | next | Python » 3.6.5 Documentation » Python Documentation contents What’s New in Python What’s New In ...

    python模块

    * decimal:python中的float使用双精度的二进制浮点编码来表示的,这种编码导致了小数不能被精确的表示,例如0.1实际上内存中为0.100000000000000001,还有3*0.1 == 0.3 为False. decimal就是为了解决类似的问题的,...

    a38_decimal-0.1.4-py3-none-any.whl

    Python安装包,亲测可用。使用pip install 文件名.whl安装使用

    Python如何安装第三方模块

    Python中有哪几种方法安装第三方模块,安装Python第三方模块的方法有很多,这里介绍三种方法安装第三方模块。 【方法一】: 通过setuptools来安装python模块 首先下载 ...

    decimal.js - JavaScript的任意精度Decimal类型-javascript

    无依赖性 宽平台兼容性:仅使用 JavaScript 1.5 (ECMAScript 3) 功能全面的文档和测试集包括一个 TypeScript 声明文件:decimal.d.ts 该库类似于 bignumber.js,但这里的精度是根据有效数字而不是小数位指定的,并且...

    Windows下Python3.6安装第三方模块的方法

    3.选择安装的属性,Documentation、pip、tcl/tk and IDLE 必须安装,tcl/tk and IDLE是Python环境的开发环境窗口,pip用来安装numpy等package。  我是选择全部安装。    4.选择安装路径,记住安装路径后面安装...

    PyPI 官网下载 | decimal_monkeypatch-0.4.3-py2-none-any.whl

    资源来自pypi官网。 资源全名:decimal_monkeypatch-0.4.3-py2-none-any.whl

    Python Tutorial 入门指南3.6英文版

    11.8. Decimal Floating Point Arithmetic 126 12. Virtual Environments and Packages 127 12.1. Introduction 127 12.2. Creating Virtual Environments 128 12.3. Managing Packages with pip 129 13. What Now? ...

    浅谈MySQL中float、double、decimal三个浮点类型的区别与总结

    下表中规划了每个浮点类型的存储大小和范围: 类型 大小 范围(有符号) 范围(无符号) 用途 ...(-3.402 823 466 E+38,-1.175 494 351 E-38),0,(1.175 494 351 E-38,3.402 823 466 351 E+38) ...

    Python Cookbook, 2nd Edition

    Doing Decimal Arithmetic Recipe 3.13. Formatting Decimals as Currency Recipe 3.14. Using Python as a Simple Adding Machine Recipe 3.15. Checking a Credit Card Checksum Recipe 3.16. Watching ...

Global site tag (gtag.js) - Google Analytics