Transform float to int so that every information i

2019-07-31 08:51发布

问题:

In Python, I receive two floats e.g.

a = 0.123456
b = 0.012340

and a precision

p = 0.000001

that tells me there will be no digits beyond the 6th decimal of the floats. I want to transform the floats to two integers, so that every information they carry is represented in the integers.

int_a = 137632
int_b = 12340

The solution in this case is obviously to multiply them by 1000000, but I can't figure out a smart way to get there. I tried the workaround to get the number of digits in p by:

len(str(p))-1 //-1 because of the dot.

But:

>>> str(p)
>>> 1e-06

Well I could replace the "-" by a "+" in the string and transform it back to a float, but this seems for me to be a pretty ugly approach and I thought there must be a much cleaner, mathematical way to do that. Any suggestion?

回答1:

Why you just do not multiply a and b with 1/p ?

int(a * 1/p) 
int(b * 1/p)

You exactly do not need python (or its string methods) other than converting resulting floats to integer, just arithmetics -))