Skip to content

Commit 2457104

Browse files
committed
BUG19225481: Fix floating point inaccuracy with Python v2
Fix Connector/Python truncating digits from float values with Python v2. This was not happening with Python v3 since str() function in v3 does not truncate digits while converting floats to string. This was resolved by using repr() instead of str() for floating point values while converting them to string. A unit test has been added for BUG19225481.
1 parent aa15416 commit 2457104

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

lib/mysql/connector/conversion.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,10 @@ def quote(self, buf):
138138
"""
139139
if isinstance(buf, NUMERIC_TYPES):
140140
if PY2:
141-
return str(buf)
141+
if isinstance(buf, float):
142+
return repr(buf)
143+
else:
144+
return str(buf)
142145
else:
143146
return str(buf).encode('ascii')
144147
elif isinstance(buf, type(None)):

tests/test_bugs.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2640,3 +2640,41 @@ def test_linestring(self):
26402640
cur.execute('DROP TABLE IF EXISTS BugOra19164627')
26412641
cur.close()
26422642
cnx.close()
2643+
2644+
2645+
class BugOra19225481(tests.MySQLConnectorTests):
2646+
"""BUG#19225481: FLOATING POINT INACCURACY WITH PYTHON v2
2647+
"""
2648+
def setUp(self):
2649+
config = tests.get_mysql_config()
2650+
self.cnx = connection.MySQLConnection(**config)
2651+
self.cursor = self.cnx.cursor()
2652+
2653+
self.tbl = 'Bug19225481'
2654+
self.cursor.execute("DROP TABLE IF EXISTS %s" % self.tbl)
2655+
2656+
create = 'CREATE TABLE {0}(col1 DOUBLE)'.format(
2657+
self.tbl)
2658+
2659+
self.cursor.execute(create)
2660+
2661+
def tearDown(self):
2662+
self.cursor.execute("DROP TABLE IF EXISTS %s" % self.tbl)
2663+
self.cursor.close()
2664+
self.cnx.close()
2665+
2666+
def test_columns(self):
2667+
values = [
2668+
(123.123456789987,),
2669+
(234.234,),
2670+
(12.12,),
2671+
(111.331,),
2672+
(0.0,),
2673+
(-99.99999900099,)
2674+
]
2675+
stmt = "INSERT INTO {0} VALUES(%s)".format(self.tbl)
2676+
self.cursor.executemany(stmt, values)
2677+
2678+
stmt = "SELECT * FROM {0}".format(self.tbl)
2679+
self.cursor.execute(stmt)
2680+
self.assertEqual(values, self.cursor.fetchall())

0 commit comments

Comments
 (0)