heyrolled
heyrolled

Reputation: 461

How do I force a number to 10 decimal places in Ruby on Rails?

I have latitude and longitude values in my database out to 10 decimal places:

+----+---------------+-----------------+
| id | lat           | lng             |
+----+---------------+-----------------+
| 55 | 34.4208305000 | -119.6981901000 |
| 56 | 30.2671530000 |  -97.7430608000 |

I need to query the db for a match, but my current variable is a float with only 6 decimal places:

self.lat => 30.267153

How can I convert my float to have the extra decimal places so I get a match?

myloc = Marker.where("lat = ?", self.lat)

I've seen Decimal and BigDecimal docs. Are those the best approach?

Ruby 1.8.7, Rails 3. Thanks for any advice.

Upvotes: 16

Views: 8762

Answers (2)

Phrogz
Phrogz

Reputation: 303549

You can use sprintf—or it's simpler brother String#%—to format your floating point number as a string with 10 decimals:

f = 30.267153
s = "%0.10f" % f
#=> "30.2671530000"

This seems fishy to me, though; what types of fields are your lat and lng columns? What RDBMS are you using? Do you really want to be comparing floating point values exactly? Do you really want to be storing them as strings?

Upvotes: 27

fl00r
fl00r

Reputation: 83680

you can try this:

"%.10f" % self.lat

Upvotes: 7

Related Questions