取整
-----
一般来说,Python中的函数、运算等默认取整
取整函数有:
`int(x=0)` -- 返回整数位
`math.floor(x)` -- 返回小于参数x的最大整数,即对浮点数向下取整
~~~
int(1.8) # 1
int(-1.8) # -1
import math
math.floor(1.8) # 1
math.floor(-1.8) # -2
~~~
四舍五入
---------
以下情况会采用四舍五入:
1. round()函数
2. `type==f`时的字符串格式化
注意:以上均受 计算机中浮点数的不精确性影响
#### `type==f`时的字符串格式化:
按照`.precision`指定精度表达,默认精度6
~~~
from decimal import Decimal
Decimal(1.5) # Decimal('1.5')
Decimal(1.55) # Decimal('1.5500000000000000444089209850062616169452667236328125')
Decimal(1.555) # Decimal('1.5549999999999999378275106209912337362766265869140625')
'--{:f}--{:.1f}--{:.2f}--'.format(1.5, 1.55, 1.555) # '--1.500000--1.6--1.55--'
~~~
#### round()
四舍五入
~~~
round(...)
round(number[, ndigits=0]) -> number
~~~
- 默认精度 - 0
- 受 计算机中浮点数的不精确性影响
~~~
round(1.234567) # 1
round(1.234567, 4) # 1.2346
# python2中:五入为远离0的最近倍数
round(0.5) # 1
round(-0.5) # -1
round(0.4) # 0
round(-0.4) # 0
# python3中:五入为最近的偶数倍数
round(0.5) # 0
round(-0.5) # 0
round(0.4) # 0
round(-0.4) # 0
~~~
- 前言
- Python编程规范
- 编码
- 代码
- 缩进、行宽、引号、空行
- 空格
- 换行
- import
- 注释
- 代码注释
- 文档注释(Docstring)
- 命名规范
- 数据结构
- 变量
- 变量作用域
- 命名空间
- 作用域
- python作用域
- 对象
- 序列
- 可迭代对象
- 迭代器
- 生成器
- 可迭代对象 & 迭代器 & 生成器
- 整数池 & 字符串intern
- 数据类型
- 数字
- int
- float
- NaN
- 四舍五入 & 取整
- 列表
- 元组
- 字典
- 集合
- 字符串
- 字符集&字符编码
- 字符串&字节串
- 字符串函数
- 字符串格式化
- str.format
- Formatted string literals
- format函数
- string.Formatter类
- %
- Format String Syntax
- Format Specification Mini-Language
- fill
- align
- sign
- #
- 0
- width
- grouping_option
- .precision
- type
- locale
- Python3 locale 模块
- 语句
- 运算符
- if/else
- for...in
- while
- break/continue
- 函数
- 函数
- 函数参数
- 递归函数
- 匿名函数
- 高阶函数
- map
- reduce
- filter
- sorted
- 返回函数
- 闭包
- 装饰器
- 函数装饰器
- 带参数的装饰器
- 类装饰器
- 带参数的类装饰器
- 偏函数
- 面向对象
- 类 & 实例
- 属性
- 方法
- 访问限制
- 继承
- 新式类 & 经典类
- MRO
- MixIn
- 模块
- 特殊变量
- 编写模块
- 引入 & 重载
- 搜索模块
- 第三方模块
- 常见模块
- 标准库
- os
- sys
- datetime
- re
- urllib
- time/datetime
- threading
- multiprocessing
- builtins
- help
- range
- enumerate
- 异同
- str() repr() ascii()
- exit()、sys.exit()、os._exit()
- 数据库
- mysql
- 错误、调试、测试
- 异常
- 异常处理
- 自定义异常
- 抛出异常
- 调试
- logging
- pdb
- 线程&&进程
- 线程
- 杂
- python 脚本传参
- python无关
- redis
- mongo
- linux
- mysql简略