大家好,又见面了,我是你们的朋友全栈君。
>>> x = 3.1415926>>> print("%.2f" % x)3.14>>>
>>> x = 3.1415926>>> round(x, 2)3.14>>>
round()函数的官方定义:
def round(number, ndigits=None): # real signature unknown; restored from __doc__
""" round(number[, ndigits]) -> number Round a number to a given precision in decimal digits (default 0 digits). This returns an int when called with one argument, otherwise the same type as the number. ndigits may be negative. """
return 0
decimal 英 /’desɪm(ə)l/ 小数的 quantize 英 /’kwɒntaɪz/ 量化
>>> from decimal import Decimal
>>> x = 3.1415926
>>> Decimal(x).quantize(Decimal("0.00"))
Decimal('3.14')
>>> a = Decimal(x).quantize(Decimal("0.00"))
>>> print(a)
3.14
>>> type(a)
<class 'decimal.Decimal'>
>>> b = str(a)
>>> b
'3.14'
>>> x = 3.1415926
>>> str(x).split(".")[0] + "." + str(x).split(".")[1][:2]
'3.14'
>>> import re
>>> x = 3.1415926
>>> re.findall(r"\d{1,}?\.\d{2}", str(a))
['3.14']
1、python2中除法,默认是取商
,也就是在做除法的时候你是无法获取小数部分的!
如下:
2、解决方法,就是在脚本文件中开头导入未来版本功能,如下:
from __future__ import division
import os
print(2/3)
注意:
from __future__ import division
一定要在其他模块之前导入,否则报错!
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/169795.html原文链接:https://javaforall.cn
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有