我使用SQLAlchemy的ORM在MySQL中存储一些数字。当我之后取回它们时,它们被截断,只保留了6个有效数字,因此失去了很多浮点数的精度。我想这应该有一个简单的解决方法,但我找不到如何解决。例如,以下代码:
import sqlalchemy as sa
from sqlalchemy.pool import QueuePool
import sqlalchemy.ext.declarative as sad
Base = sad.declarative_base()
Session = sa.orm.scoped_session(sa.orm.sessionmaker())
class Test(Base):
__tablename__ = "test"
__table_args__ = {'mysql_engine':'InnoDB'}
no = sa.Column(sa.Integer, primary_key=True)
x = sa.Column(sa.Float)
a = 43210.123456789
b = 43210.0
print a, b, a - b
dbEngine = sa.create_engine("mysql://chore:BlockWork33!@localhost", poolclass=QueuePool, pool_size=20,
pool_timeout=180)
Session.configure(bind=dbEngine)
session = Session()
dbEngine.execute("CREATE DATABASE IF NOT EXISTS test")
dbEngine.execute("USE test")
Base.metadata.create_all(dbEngine)
try:
session.add_all([Test(x=a), Test(x=b)])
session.commit()
except:
session.rollback()
raise
[(a,), (b,)] = session.query(Test.x).all()
print a, b, a - b
生产
43210.1234568 43210.0 0.123456788999
43210.1 43210.0 0.0999999999985
我需要一个解决方案来实现它
43210.1234568 43210.0 0.123456788999
43210.1234568 43210.0 0.123456788999