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
kayseen
V2EX  ›  Python

Python 中保留小数点后 2 位但是不进行四舍五入

  •  
  •   kayseen · 2019-11-26 16:30:28 +08:00 · 3742 次点击
    这是一个创建于 1604 天前的主题,其中的信息可能已经有所发展或是发生改变。

    如题,

    python 中的 round 在进行保留小数点后面位数的时候,小数点前面是奇数才进 1,偶数不进 1

    如果需要对10.93909保留小数点后 2 位,但是不需要四舍五入,大家有好的方法吗?

    tips: 网上的方法有: 1.转换成 str,然后 split,再拼接,再 float 转换,最后是 float 格式 2.str(10.93909).partition('.'), 然后再补'0',最后是 str 格式 3.re 匹配, re.findall(r"\d{1,}?.\d{2}", str(10.93909))

    方法虽然可以实现,想问大家 python 有咩有更好的实现方法?

    5 条回复    2019-11-27 15:00:17 +08:00
    crella
        1
    crella  
       2019-11-26 16:33:29 +08:00 via Android
    int(10.93909*100)/100,当然这不是 python 代码。
    noobsheldon
        2
    noobsheldon  
       2019-11-26 16:38:40 +08:00   ❤️ 1
    关键字 decimal round_half_even
    imn1
        3
    imn1  
       2019-11-26 16:44:33 +08:00
    如果不用后续计算,只是输出的话,str 的 format 更好,不会出现浮点不可预料的问题
    起码比 split 简单

    如果要计算,我用#1 的方案多
    yucongo
        4
    yucongo  
       2019-11-27 11:57:01 +08:00
    math.trunc(10.930 * 10 ** 2) / 10 ** 2
    capo
        5
    capo  
       2019-11-27 15:00:17 +08:00
    num*100//1/100
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3855 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 04:23 · PVG 12:23 · LAX 21:23 · JFK 00:23
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.