python 有效位数和小数位数两种修约方式(四舍六入五成双)

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,将上一位变为偶数(即奇数时进位成偶数,偶数时不进位)。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值