3

I am storing gps coordinates in Rails 4/Ruby 2.1 and am running into an odd issue. My migration has this:

t.decimal :latitude, precision: 9, scale: 6
t.decimal :longitude, precision: 9, scale: 6

This results in Rails using BigDecimals to store them. However they get corrupted with certain numbers:

2.1.5 :001 > p BigDecimal.new(-122.41146504878998,9)
#<BigDecimal:6f60da0,'-0.122E3',9(27)>
 => #<BigDecimal:6f60da0,'-0.122E3',9(27)> 
2.1.5 :002 > p BigDecimal.new(-122.41146504878999,9)
#<BigDecimal:6f681b8,'-0.122411465E3',18(27)>
 => #<BigDecimal:6f681b8,'-0.122411465E3',18(27)> 

The first example loses all precision for some reason, resulting in -122.000000 being stored in the db.

I am guessing this is because the intermediate representation is a float in both irb and perhaps in the json parser.

How do I avoid this? I am receiving this data in a json body, is the conversion from json where the precision is lost? Should I store/transmit these as strings?

rubby22
  • 31
  • 2
  • What database are you using? What does the log show for the request params? What does your controller code look like? What do the values look like when you use `inspect` in the controller? – Jordan Running Feb 14 '15 at 00:07
  • There's not an answer yet, but http://stackoverflow.com/questions/28295583/why-are-my-bigdecimal-objects-initialized-with-unexpected-rounding-errors seems to be a similar issue – Frederick Cheung Feb 15 '15 at 19:12

0 Answers0