zoukankan      html  css  js  c++  java
  • Python取整及保留小数小结

    1.int() 向下取整 内置函数 

    1 n = 3.75
    2 print(int(n))
    >>> 3
    3 n = 3.25 4 print(int(n))
    >>> 3

    2.round() 四舍五入 内置函数

    1 n = 3.75
    2 print(round(n))
    >>> 4
    3 n = 3.25 4 print(round(n))
    >>> 3

    3. floor() 向下取整 math模块函数 

    floor的英文释义:地板。顾名思义也是向下取整

    1 import math
    2 n = 3.75
    3 print(math.floor(n))
    >>> 3
    4 n = 3.25 5 print(math.floor(n))
    >>> 3

    4.ceil()向上取整 math模块函数

    ceil的英文释义:天花板。

    1 import math
    2 n = 3.75
    3 print(math.ceil(n))
    >>> 4
    4 n = 3.25 5 print(math.ceil(n))
    >>> 4

    5.modf() 分别取整数部分和小数部分 math模块函数

    该方法返回一个包含小数部分和整数部分的元组
    1 import math
    2 n = 3.75
    3 print(math.modf(n))
    >>> (0.75, 3.0)
    4 n = 3.25 5 print(math.modf(n))
    >>> (0.25, 3.0)
    6 n = 4.2 7 print(math.modf(n))
    (0.20000000000000018, 4.0)

    最后一个的输出,涉及到了另一个问题,即浮点数在计算机中的表示,在计算机中是无法精确的表示小数的,至少目前的计算机做不到这一点。上例中最后的输出结果只是 0.2 在计算中的近似表示。Python 和 C 一样, 采用 IEEE 754 规范来存储浮点数。

    以上内容源自:https://www.jb51.net/article/102248.htm

    6.保留一位小数

    三种方法:

    1 print(round(10/3,1))
    2 print('%.1f'%(10/3))
    3 print(format((10/3),'.1f'))
    >>> 3.3
  • 相关阅读:
    500桶酒中有一桶毒酒
    查看docker run参数(亲测实用)
    ubuntu密码忘记-备份
    python sklearn2pmml
    javafx弹窗显示错误堆栈
    Java实现新开一个进程
    MockServer调试通过,本地通过浏览器可以打开对应web网页
    java 实现Put request
    JAVA发送HttpClient请求及接收请求完整代码实例
    我还是很喜欢你
  • 原文地址:https://www.cnblogs.com/sen-c7/p/9473224.html
Copyright © 2011-2022 走看看