如何在Python中移动小数点?

如何在Python中移动小数点?,python,decimal,Python,Decimal,我现在用下面的公式计算两次的差值。输出-输入非常快,因此我不需要显示仅为0.00的小时和分钟。在Python中如何实际移动小数点 def time_deltas(infile): entries = (line.split() for line in open(INFILE, "r")) ts = {} for e in entries: if " ".join(e[2:5]) == "OuchMsg out: [O]":

我现在用下面的公式计算两次的差值。输出-输入非常快,因此我不需要显示仅为0.00的小时和分钟。在Python中如何实际移动小数点

def time_deltas(infile): 
    entries = (line.split() for line in open(INFILE, "r")) 
    ts = {}  
    for e in entries: 
        if " ".join(e[2:5]) == "OuchMsg out: [O]": 
            ts[e[8]] = e[0]    
        elif " ".join(e[2:5]) == "OuchMsg in: [A]":    
            in_ts, ref_id = e[0], e[7] 
            out_ts = ts.pop(ref_id, None) 
            yield (float(out_ts),ref_id[1:-1], "%.10f"%(float(in_ts) - float(out_ts)))

INFILE = 'C:/Users/kdalton/Documents/Minifile.txt'
print list(time_deltas(INFILE))

就像你在数学上做的一样

a = 0.01;
a *= 10; // shifts decimal place right
a /= 10.; // shifts decimal place left
或者使用模块


扩展公认的答案;这是一个函数,它将移动你给它的任何数字的小数位。如果小数点参数为0,则返回原始数字。为保持一致性,始终返回浮点类型

def moveDecimalPoint(num, decimal_places):
    '''
    Move the decimal place in a given number.

    args:
        num (int)(float) = The number in which you are modifying.
        decimal_places (int) = The number of decimal places to move.
    
    returns:
        (float)
    
    ex. moveDecimalPoint(11.05, -2) returns: 0.1105
    '''
    for _ in range(abs(decimal_places)):

        if decimal_places>0:
            num *= 10; #shifts decimal place right
        else:
            num /= 10.; #shifts decimal place left

    return float(num)

print (moveDecimalPoint(11.05, -2))
def move_点(数字、移位、基数=10):
"""
>>>移动_点(1,2)
100
>>>移动_点(1,-2)
0.01
>>>移动_点(1,2,2)
4.
>>>移动_点(1,-2,2)
0.25
"""
返回编号*基本**班次

注意整数除法。如果
a
是一个整数,这可能会让一些人挠头。也许把最后一行改成
a/=10.
。谢谢!是的……我想我把它弄得比应该的更复杂了:这是@TylerCrompton关于整数除法的正确说法的补充。作为一个标准(无论我打算做什么),我的脚本顶部总是有来自未来导入部门的
。这样我就省去了很多挠头的麻烦……)(哦,顺便说一句,这在Python3中已经解决了)。这些操作并不像您从二进制移位运算符()中所期望的那样,由于舍入错误而彼此相反。这不是一种很好的方法,因为您会给出舍入错误。不是吹嘘,但对于一些人来说,一种非常简单的方法可能是执行
re.sub(r'[a-z]“,”,number.lower())
,然后执行
int(number)
float(number)
。如果要将小数点除以或乘以10,请使用simple;)
def moveDecimalPoint(num, decimal_places):
    '''
    Move the decimal place in a given number.

    args:
        num (int)(float) = The number in which you are modifying.
        decimal_places (int) = The number of decimal places to move.
    
    returns:
        (float)
    
    ex. moveDecimalPoint(11.05, -2) returns: 0.1105
    '''
    for _ in range(abs(decimal_places)):

        if decimal_places>0:
            num *= 10; #shifts decimal place right
        else:
            num /= 10.; #shifts decimal place left

    return float(num)

print (moveDecimalPoint(11.05, -2))