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))
Use str. format() with “{:. 2f}” as string and float as a number to display 2 decimal places in Python.
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.
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.
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.
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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With