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.


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?


你可以试试这个:

"%.10f" % self.lat
链接地址: http://www.djcxy.com/p/85826.html

上一篇: 导出已消失,异常规格已弃用。 这会影响你的代码吗?

下一篇: 如何在Ruby on Rails中将数字强制为10个小数位?