开发者

How to bind a double precision using psycopg2

开发者 https://www.devze.com 2022-12-29 16:10 出处:网络
I\'m trying to bind a float to a postgresql double precision using psycopg2. ele = 1.0/3.0 dic = {\'name\': \'test\', \'ele\': ele}

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'
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号