How can I convert a string ("longint") to float if the number of decimals are known?

Viewed 43

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.

I have tried to do conversion to char-array then adding a . char then merging the char-array but that feels super irrational

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?

1 Answers

You can convert to float then divide by 10^7

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