Transform float to int so that every information is preserved OR how to get the lenght of a long float

不想你离开。 提交于 2019-12-24 18:02:47

问题


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 -))



来源:https://stackoverflow.com/questions/48815210/transform-float-to-int-so-that-every-information-is-preserved-or-how-to-get-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!