import decimal
import math
import myglobal
import logging
def round_half_even(num_str,p):
if num_str=="":
return ""
zstr="0."+p*"0"
logging.info([num_str,p,zstr])
return decimal.Decimal(num_str).quantize(decimal.Decimal(zstr),rounding=decimal.ROUND_HALF_EVEN)
def remove_exponent(d):
return d.quantize(decimal.Decimal(1)) if d == d.to_integral() else d.normalize()
class Xy():
def __init__(self,type1=0,num1=4):
self.type=type1
self.num=num1
pass
def xiuyue(self,v):
logging.info([v,type(v)])
if v=="":
return v
if self.type==0:
logging.info("youxiao")
# r=float(f'%.{self.num}g' % myglobal.myfloat(v))
d=decimal.Context(prec=self.num,rounding=decimal.ROUND_HALF_EVEN).create_decimal(v)
d=remove_exponent(d)
r=str(d)
elif self.type==1:
logging.info("xiaoshu")
d=round_half_even(v,self.num)
r=str(d)
else:
logging.info("none")
r=v
logging.info(r)
return r
def kb(a):
if a== "" or a == 0:
return ""
else:
return a
def mround(number, multiple):
return multiple * round(number / multiple)
def count_decimal_places2(num):
d=decimal.Decimal(str((num)))
return -d.as_tuple().exponent
def test2():
x=Xy()
# print(x.xy(math.pi))
print(x.xiuyue("3.1415"))
print(x.xiuyue("3.1425"))
x=Xy()
# x.type=Xy_type.XiaoshuWei
# x.num=3
print(x.xiuyue("3.1415"))
print(x.xiuyue("3.1425"))
print(round_half_even("3.1415",3))
print(round_half_even("3.1425",3))
if __name__=="__main__":
# test1()
# test2()
test2()
四舍六入五成双是指舍入位正好为5,舍入位后面都是0,将上一位变为偶数(即奇数时进位成偶数,偶数时不进位)。