I'm trying to bind a float to a postgresql double precision using psycopg2.
ele = 1.0/3.0
dic = {'name': 'test', 'ele': ele}
sql = '''insert into waypoints (name, elevation) values (%(name)s, %(ele)s)'''
cur = db.cursor()
cur.execute(sql, dic)
db.commit()
sql = """select elevation from waypoints where name = 'test'"""
cur.execute(sql_out)
ele_out = cur.fetchone()[开发者_C百科0]
ele_out
0.33333333333300003
ele
0.33333333333333331
Obviously I don't need the precision, but I would like to be able to simply compare the values. I could use the struct module and save it as a string, but thought there should be a better way. Thanks
The reason you're getting this problem is the following line of code:
sql = '''insert into waypoints (name, elevation) values (%(name)s, %(ele)s)'''
because when the float is converted into a string here, you don't get all of the digits that you're expecting. For instance,
str(ele)
produces
'0.333333333333'
Changing the line to
sql = '''insert into waypoints (name, elevation) values (%(name)s, %(ele).17f)'''
I believe will give you your desired result because
'%(ele).17f' % dic
produces
'0.33333333333333331'
精彩评论