V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
mili8908
V2EX  ›  Python

Python 保留小数后精度问题

  •  
  •   mili8908 · 2018-08-22 16:58:31 +08:00 · 4117 次点击
    这是一个创建于 2315 天前的主题,其中的信息可能已经有所发展或是发生改变。
    a = 0.9987623
    # 将 a 保留两位小数得到
    a = 0.99
    
    8 条回复    2018-08-23 13:43:59 +08:00
    zh0408
        1
    zh0408  
       2018-08-22 17:09:14 +08:00
    round()
    gnozix
        2
    gnozix  
       2018-08-22 17:14:39 +08:00
    format
    mili8908
        3
    mili8908  
    OP
       2018-08-22 17:21:28 +08:00
    @zh0408
    In [2]: a = 0.998765

    In [3]: round(a,2)
    Out[3]: 1.0
    gimp
        4
    gimp  
       2018-08-22 17:26:01 +08:00   ❤️ 1
    >>> r = lambda f: f - f % 0.01
    >>> r(2.368)
    2.36
    >>> r(2.36888888)
    2.36
    >>> r(2.323)
    2.32
    >>> r(2.326)
    2.32

    摘自: https://www.reddit.com/r/learnpython/comments/4nj5gu/how_to_get_float_to_two_decimal_places_without/
    chenxingyu1021
        5
    chenxingyu1021  
       2018-08-22 17:38:15 +08:00   ❤️ 1
    int(a*100)/100
    lxy42
        6
    lxy42  
       2018-08-22 17:39:50 +08:00
    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?

    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')
    mili8908
        7
    mili8908  
    OP
       2018-08-23 09:16:58 +08:00
    @gimp 这就厉害了
    pyse
        8
    pyse  
       2018-08-23 13:43:59 +08:00
    你们的为什么没有四舍五入呢???


    >>> a = 0.9987623

    >>> print("%.2f" %a)

    1.00
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1047 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 19:25 · PVG 03:25 · LAX 11:25 · JFK 14:25
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.