当前位置: 首页 > news >正文

Python内置函数(55)——round

英文文档:

round(number[, ndigits])
Return the floating point value number rounded to ndigits digits after the decimal point. If ndigits is omitted, it returns the nearest integer to its input. Delegates to number.__round__(ndigits).
For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). The return value is an integer if called with one argument, otherwise of the same type as number.
Note:
The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.  
说明:

1. round函数用于对浮点数进行四舍五入求值,具体保留几位小数,以传入的ndigits参数来控制。

>>> round(1.1314926,1)
1.1
>>> round(1.1314926,5)
1.13149
2. ndigits参数为可选参数,当不传入时,即以默认保留0位小数进行取整,返回的是整数。

>>> round(1.1314926)
1
3. ndigits参数传入0时,虽然与不传入ndigits参数一样保留0位小数进行四舍五入,但是返回的值是浮点型。

>>> round(1.1314926,0)
1.0
4. ndigits参数小于0时,对整数部分进行四舍五入,ndigits参数控制了对浮点数的整数部分的后几位进行四舍五入,小数部分全部清0,返回类型是浮点数。如果传入的浮点数的整数部分位数小于ndigits参数绝对值,则返回0.0.

>>> round(11314.926,-1)
11310.0
>>> round(11314.926,-3)
11000.0
>>> round(11314.926,-4)
10000.0
>>> round(11314.926,-5)
0.0
5. round四舍五入时是遵循靠近0原则,所以-0.5和0.5进行0位四舍五入,返回的都是0.

>>> round(0.5)
0
>>> round(-0.5)
0
6. 对于浮点数求四舍五入有一个陷阱,有些四舍五入结果不像预期那样,比如round(2.675, 2) 的结果是2.67 而不是预期的 2.68,这不是bug,而是浮点数在存储的时候因为位数有限,实际存储的值和显示的值有一定误差。

>>> round(2.675, 2)
2.67
7. 对整数也能进行round操作,返回值也是整形。

>>> round(134567)
134567
>>> round(134567,0)
134567
>>> round(134567,1)
134567
>>> round(134567,2)
134567
>>> round(134567,-2)
134600
>>> round(134567,-6)
0

相关文章:

  • 《C++语言程序设计》大作业(三个模块)
  • R语言使用lightgbm包构建多分类的LightGBM模型、使用predict函数和训练好的模型进行预测推理、将推理后的概率值转化为预测标签
  • 计算机毕业设计Java企业售后服务管理系统(源代码+数据库+系统+lw文档)
  • Day19 | 每天五道题
  • 02.java课复习
  • 深入理解ReentrantReadWriteLock源码
  • 【C++基础】 MyArray 自己实现动态数组 类模板
  • JavaScript中常用的高阶函数
  • 快来给你的宠物视频加个表情特效吧
  • 论文笔记|DeepWalk
  • STM32的光敏检测自动智能窗帘控制系统proteus设计
  • week14|week15 查阅文章总结
  • 编写一个方法,去掉一个数组的重复元素。
  • HTML做一个简单的页面(纯html代码)地球专题学习网站
  • Neuroscout:可推广和重复利用的fMRI研究统一平台
  • Arduino开发实例-DIY超声波传感器避障机器人
  • QuTrunk与MindSpore量子神经网络初探
  • Docker配置主从复制
  • 助农销售平台毕业设计,农产品销售管理系统设计与实现,毕业设计怎么写论文源码开题报告需求分析怎么做
  • FOR ALL ENTRIES 优化
  • 电加热油锅炉工作原理_电加热导油
  • 大型电蒸汽锅炉_工业电阻炉
  • 燃气蒸汽锅炉的分类_大连生物质蒸汽锅炉
  • 天津市维修锅炉_锅炉汽化处理方法
  • 蒸汽汽锅炉厂家_延安锅炉厂家
  • 山西热水锅炉厂家_酒店热水 锅炉
  • 蒸汽锅炉生产厂家_燃油蒸汽发生器
  • 燃煤锅炉烧热水_张家口 淘汰取缔燃煤锅炉
  • 生物质锅炉_炉
  • 锅炉天然气_天燃气热风炉