这篇教程python保存两位小数的多种方法汇总写得很实用,希望能帮到您。
一、保留两位小数 且 做四舍五入处理四舍六入五成双, 四舍六入五凑偶的意思, 根据百度词条的解释如下: (1)当精确位后面一位的数字是1-4的时候,舍去 (2)当精确位后面一位的数字是6-9的时候,进1位 (3)当精确位后面一位的数字是5的,此时需要看这个5后面是否还有值。如果5后面有值(0忽略),则直接进位; (4)如果5后面没值或值为0,则需要判断5前面的值是偶数还是奇数。 (5)如果5前面是偶数,不进位;如果是奇数,进位。
1、使用字符串格式化>>> x = 3.1415926>>> print("%.2f" % x)3.14>>>
2、使用python内置的round() 函数>>> 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
3、使用python内置的decimal模块decimal 英 /'des python python自动化测试工具Helium使用示例 |