Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I shift the decimal place in Python?

Tags:

python

decimal

I'm currently using the following to compute the difference in two times. The out - in is very fast and thus I do not need to display the hour and minutes which are just 0.00 anyway. How do I actually shift the decimal place in 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))
like image 607
eunhealee Avatar asked Dec 02 '11 21:12

eunhealee


People also ask

How do you place 2 decimal places in Python?

Use str. format() with “{:. 2f}” as string and float as a number to display 2 decimal places in Python.

How do you shift decimal places?

If there IS a decimal point, move it to the right the same number of places that there are 0s. When dividing by 10, 100, 1000 and so on, move the decimal point to the left as many places as there are 0s. So when dividing by 10, move the decimal point one place, by 100 two places, by 1000 three places and so on.

Can the value before the decimal point change in Python?

But the value before the decimal point (.) never changes. When we round a value, however, then then the number before . can change. Now that we got a custom function that truncates to a certain number of decimal places, let’s see how we use it.

How to trunc decimal places in Python?

When we truncate values, we remove the decimal portion of a value. But what if we want to keep a certain number of decimal places? Let’s see how to program that in Python. With Python’s math.trunc () function we truncate floating-point values into whole numbers (Python Docs, n.d.). That turns 4.578 into 4 and makes -2.9 into -2.

What is the decimal shift () method in Python?

Python | Decimal shift () method Last Updated : 05 Sep, 2019 Decimal#shift () : shift () is a Decimal class method which returns the shifted copy of x, y times

How to round float to 2 decimal places in Python?

To round the float value to 2 decimal places, you have to use the Python round (). The round function is the common function to use and requires only two arguments. If you want to round to 2 decimal places, you have to pass 2 as the value of the second argument.


1 Answers

def move_point(number, shift, base=10):
    """
    >>> move_point(1,2)
    100
    >>> move_point(1,-2)
    0.01
    >>> move_point(1,2,2)
    4
    >>> move_point(1,-2,2)
    0.25
    """
    return number * base**shift
like image 179
Cees Timmerman Avatar answered Oct 20 '22 06:10

Cees Timmerman