【问题标题】:Control decimal division precision in MySQLdb在 MySQLdb 中控制小数除法精度
【发布时间】:2009-12-16 20:18:28
【问题描述】:

MySQLdb 有点奇怪,它似乎总是返回一个 Decimal 对象,其有效数字比除法运算的分子多 2 个。

如果分母比较大,这意味着有时结果会被截断为零:

>>> import MySQLdb
>>> db = MySQLdb.connect(.....)
>>> c = db.cursor();
>>> c.execute("select 1000/ 20990933630")
1L
>>> c.fetchall()
((Decimal("0.0000"),),)
>>> c.execute("select 1000.0000000000000000000000/ 20990933630")
1L
>>> c.fetchall()
((Decimal("4.763961516084313397E-8"),),)
>>> c.execute("select (1000 + 0.000000000000000000000) / 20990933630")
1L
>>> c.fetchall()
((Decimal("4.76396151608431340E-8"),),)

我可以强制浮点除法吗?有没有比向所有内容添加 0.0000000000 更优雅的方法?

【问题讨论】:

    标签: python mysql


    【解决方案1】:

    您可以更改 div_precision_increment 变量。默认为 4。

    http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_div_precision_increment

    这是一个使用你的部门的例子:

    mysql> select 1000/ 20990933630;
    +-------------------+
    | 1000/ 20990933630 |
    +-------------------+
    |            0.0000 | 
    +-------------------+
    1 row in set (0.00 sec)
    
    mysql> set local div_precision_increment = 30;
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> select 1000/ 20990933630;
    +----------------------------------+
    | 1000/ 20990933630                |
    +----------------------------------+
    | 0.000000047639615160843133969739 | 
    +----------------------------------+
    1 row in set (0.00 sec)
    
    mysql> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      • 2020-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多