Reputation: 879
I am using gmaps4rails and in order to store the exact coordinates from a user's marker, I use string data type for latitude and longitude.
However, even though my lat/long fields on the page get filled with the entire numbers (i.e. 37.79560594600171
and 30.794677734375
), when I check the log, these are the numbers that are inserted: 37.818138
and 30.7336038
. They are approximated somehow?!
BUT then if I edit that item from the edit screen, the entire values get stored without a problem. I can see that in both my log and db.
I also tried with decimals (with 16 precision and 14 scale) instead of strings. But still, my database would store just an approximated part of a long number and then fill the rest with 0. For instance, something like this: 44.31223760000000
.
I am using Ruby 2 with Rails 4 and mysql as database. But I think the problem would be somehow with activerecord, since it is the one that stores the values in the db?
These are from my new/edit form:
<%= f.label :latitude %>
<%= f.text_field :latitude %>
<%= f.label :longitude %>
<%= f.text_field :longitude %>
Any idea would be appreciated. Thanks!
Upvotes: 1
Views: 113
Reputation: 72504
I'm guessing there are some hidden conversions happening.
Here are a few things you can check:
(1) Whenever you are printing numbers to the console the output is generated by to_s
which at least for floats rounds the value. (Just the returned output, not the original value)
For example (1.0/10).to_s
returns "0.1"
but %.20f" % (1.0/10)
returns "0.10000000000000000555"
If you try to hunt down your problem, I'd suggest you create a helper to print out decimal numbers without any trunction first, or find another way to display your values without having to question whether the number has been rounded or not.
(2) If you are using strings, there is no reason for ActiveRecord to truncate your input. That would be a terrible bug many applications would suffer from. It is more likely that there is another conversion happening, perhaps something like value.to_f.to_s
or similar. You can test this by inserting characters only. If your value ends up in the database as zero or nil you definitely have a hidden conversion.
(3) If you are using decimals, i.e. BigDecimal
make sure that you are using BigDecimal
only and no Float
! Explicitly or by using to_f
. That way you would introduce rounding problems, too
(4) It is also possible that your data doesn't reach your application intact, perhaps because of Javascript or HTML5 inputs (type=number
) which potentially can reduce the precision. You can verify this by printing out the entire params
hash in the controller action. (Using pp
or better ap
)
(5) Check your migration. Make sure you use the correct precision and that the given precision is applied to the database.
Upvotes: 1