首页 > 解决方案 > 如果小数位数已知,如何将字符串(“longint”)转换为浮点数?

问题描述

给定一个纬度/经度组合作为字符串:

lat = "514525865"
lon = "54892584"

我希望将它们转换为浮点数:

lat = 51.4525865
lon =  5.4892584

如您所见,小数位数是已知的,并且是 7。

我试图转换为 char-array 然后添加一个 . 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

没有错误,因为这有效,但感觉很愚蠢..有更好的功能吗?

标签: rubyfunctionoptimization

解决方案


您可以转换为浮点数,然后除以 10^7

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

推荐阅读