I have latitude and longitude values in my database out to 10 decimal places:
在我的数据库中,我有纬度和经度值,小数点后10位:
+----+---------------+-----------------+
| 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:
我需要查询db是否匹配,但我的当前变量是一个只有6位小数的浮点数:
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?
我见过十进制和BigDecimal文档。这是最好的方法吗?
Ruby 1.8.7, Rails 3. Thanks for any advice.
Ruby 1.8.7,Rails 3。谢谢你的任何建议。
2 个解决方案
#1
25
You can use sprintf
—or it's simpler brother String#%
—to format your floating point number as a string with 10 decimals:
您可以使用sprintf -或更简单的兄弟字符串#%来将浮点数格式化为10小数的字符串:
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?
这在我看来很可疑;你们的lat和液化天然气塔是什么类型的?您正在使用什么RDBMS ?你真的想要精确地比较浮点值吗?你真的想把它们存储为字符串吗?
#2
7
you can try this:
你可以试试这个:
"%.10f" % self.lat
#1
25
You can use sprintf
—or it's simpler brother String#%
—to format your floating point number as a string with 10 decimals:
您可以使用sprintf -或更简单的兄弟字符串#%来将浮点数格式化为10小数的字符串:
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?
这在我看来很可疑;你们的lat和液化天然气塔是什么类型的?您正在使用什么RDBMS ?你真的想要精确地比较浮点值吗?你真的想把它们存储为字符串吗?
#2
7
you can try this:
你可以试试这个:
"%.10f" % self.lat