python3 四舍五入(0.5可以进1)

今天做了一个题要求四舍五入,然后找了一个方法:round()可以四舍五入,

试了试1.5---》2

试了试0.5---》0   !!!! 

找了几个方法说可以的:

# 方法一:
from _pydecimal import Decimal, Context, ROUND_HALF_UP
print(Context(prec=3, rounding=ROUND_HALF_UP).create_decimal('1.32545454544'))
# 方法二:
print(round(1.32545454544* 100) / 100.0)

输出:  1.33

但是!!但是!!但是!!

输入0.5结果是0.5   ( 这个可以通过设置格式得到,原来不知道)

            

 没办法,对于有些可以,有些不可以,主要是存储十进制的时候二进制有偏差,怎么办!?

这里我自己鼓捣出一个方法(在数后面加一个很小的数,不影响计算的那种如:0.000000000001)

  print(round(0.5+0.00000000000001))
  结果  1
另外可以用下面方法:

      







========================================================最新更新=====================================================================

decimal函数使用:
  decimal()函数是用于十进制精确计算的,为的是防止浮点数后面位数不准确导致计算结果出现偏差
  prec : 设置精度(有效数字位数)
  rounding : 设置舍入舍出方式
    有多种方法
ROUND_CEILING (towards Infinity),
ROUND_DOWN (towards zero),
ROUND_FLOOR (towards -Infinity),
ROUND_HALF_DOWN (to nearest with ties going towards zero),
ROUND_HALF_EVEN (to nearest with ties going to nearest even integer),
ROUND_HALF_UP (to nearest with ties going away from zero), or
ROUND_UP (away from zero).
ROUND_05UP (away from zero if last digit after rounding towards zero would have been 0 or 5; otherwise towards zero)
View Code

                                                          

    设定小数位数

    Decimal('1.2346568355').quantize(Decimal('0.00'))

    设定有效数字

    getcontext().prec = 4





参考:
https://blog.csdn.net/qq_34979346/article/details/83827044
https://www.cnblogs.com/piperck/p/5843253.html
https://finthon.com/python-decimal/

原文地址:https://www.cnblogs.com/51python/p/11300023.html