简体   繁体   English

如果小数位数已知,如何将字符串(“longint”)转换为浮点数?

[英]How can I convert a string (“longint”) to float if the number of decimals are known?

Given a lat/lon combination as string:给定一个纬度/经度组合作为字符串:

lat = "514525865"
lon = "54892584"

I wish to convert them to floats:我希望将它们转换为浮点数:

lat = 51.4525865
lon =  5.4892584

As you can see the number of decimals is KNOWN and given to be 7.如您所见,小数位数是已知的,并且是 7。

I have tried to do conversion to char-array then adding a.我试图转换为 char-array 然后添加一个。 char then merging the char-array but that feels super irrational char 然后合并 char-array 但这感觉非常不合理

def pos_to_float(stringpos)
    chars = stringpos.chars
    chars.insert(-8,'.')
    outstring = chars.join('')
    return outstring.to_f
end

lat = "514525865"
floatlat = pos_to_float(lat)
puts floatlat

> 51.4525865

no error as this works but it feels stupid.. any better functions?没有错误,因为这有效,但感觉很愚蠢..有更好的功能吗?

You can convert to float then divide by 10^7您可以转换为浮点数,然后除以 10^7

p lat.to_f / 10 ** 7
#=> 51.4525865

You can use insert method directly.您可以直接使用插入方法。

lat.insert(2, '.').to_f
#=> 51.4525865

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM