2

I have a model that uses floating points to store geolocations. It stores the data in MySQL, using ActiveRecord, Rails 3.2.x.

c = Camping.new()
c.latitude=51.77802459999999
c.save
c.latitude
=> 51.77802459999999
c.reload
c.latitude
=> 51.778

When looking in the database, I confirm it is stored as 51.778. Other numbers are stored with more precision, I have the idea the 0 is what makes either ActiveRecord or MySQL decide to omit the rest.

What decides that the number could or should be chopped off after three digits? Is there anything to control this? Is float the correct type to store this in?

I want a precision of 6, never more, but could be less, or padded. So when 51.7780 is provided, it might be stored as 51.7780 or as 51.778000. When 51.77802459999999is provided, it could be stored as 51.778025 or as the number with full precision; I don't really care.

Relevant part from schema.rb:

  create_table "campings", :force => true do |t|
    #...
    t.float    "latitude"
    t.float    "longitude"
  end
tereško
  • 58,060
  • 25
  • 98
  • 150
berkes
  • 26,996
  • 27
  • 115
  • 206

1 Answers1

1

Apparently, MySQL is the problem, as float is described as an approximated value.

You can use decimal instead, and specify the precision and scale:

create_table "campings", :force => true do |t|
  #...
  t.decimal    "latitude",  :precision => 15, :scale => 10
  t.decimal    "longitude", :precision => 15, :scale => 10
end
gabrielhilal
  • 10,660
  • 6
  • 54
  • 81
  • Are there any downsides in storage- and lookuptime, indexing or storage-space there? For my smallscale app it won't matter the least bit; but just for clarity. – berkes Feb 13 '13 at 07:50
  • 1
    according to [High Performance MySQL](http://www.amazon.com/High-Performance-MySQL-Optimization-Replication/dp/1449314287) float points are [faster](http://books.google.co.uk/books?id=BL0NNoFPuAQC&pg=PA83&lpg=PA83#v=onepage&q&f=false). However, they are not reliable, so I believe the small improvement in performance does not worth it. – gabrielhilal Feb 13 '13 at 09:54
  • Comparison and bench-marking : http://stackoverflow.com/questions/8514167/float-vs-decimal-in-activerecord – Nimir Jun 23 '13 at 11:48