ruby - 如果小数位数已知,如何将字符串(“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
没有错误,因为这有效,但感觉很愚蠢..有更好的功能吗?
解决方案
您可以转换为浮点数,然后除以 10^7
p lat.to_f / 10 ** 7
#=> 51.4525865
推荐阅读
- swagger-2.0 - openapi 是否支持复杂类型的默认值?
- javascript - 用 javascript 构建一个文字处理器
- r - 如何在应用函数中使用 cor.test?
- reactjs - 无法理解如何从映射元素接收值
- java - 编组错误:javax.xml.bind.JAXBException:此上下文已知类或其任何超类
- android - 构建时Android Toast.makeText错误
- sql - 如何根据 OR 条件从一个表连接到多个表?
- html - 即使在自动换行时,如何为拉伸的 Flex 项目保持统一的项目高度?
- arduino - Arduino检查uint8_int的相等性
- php - 如何从查询中获得最大值?