将float转换为int,以便保留所有信息,或者如何获取long float的长度 [英] Transform float to int so that every information is preserved OR how to get the lenght of a long float
问题描述
在Python中,我收到两个浮点数,例如
In Python, I receive two floats e.g.
a = 0.123456
b = 0.012340
和精度
p = 0.000001
告诉我,浮点数的第6个小数后没有数字. 我想将浮点数转换为两个整数,以便它们携带的每个信息都以整数表示.
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
在这种情况下,解决方案显然是将它们乘以1000000,但是我想不出一种聪明的方法来达到目标. 我尝试通过以下方法获得p中的位数:
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.
但是:
>>> 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?
推荐答案
为什么不将a
和b
与1/p
相乘?
int(a * 1/p)
int(b * 1/p)
除了将结果浮点数转换为整数(仅算术-)之外,您完全不需要python(或其字符串方法)
You exactly do not need python (or its string methods) other than converting resulting floats to integer, just arithmetics -))
这篇关于将float转换为int,以便保留所有信息,或者如何获取long float的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!