使用Python舍入到2dp用于SQLITE插入

问题描述 投票:0回答:1

我正在尝试将值在python中(使用jupyter笔记本)四舍五入到2个小数位,然后将这些值插入SQLITE3,但其中一些值未四舍五入:

请求:

count = cursor.execute("""SELECT test_user,
                          SUM(CASE WHEN start >= ? THEN round(julianday(end)*24, 1) - round(julianday(start)*24, 1) ELSE 0 END),
                          FROM test_table
                          WHERE start < ?
                          GROUP BY test_user""", (sdate.to_pydatetime(), edate.to_pydatetime())).fetchall()

响应:

[('1', 0, 8.0, 8.0),
 ('2', None, None, None),
 ('3', 0, 7.0, 7.0),
 ('5', 0.20000000298023224, 0.20000000298023224, 0.20000000298023224),
 ('6', 0.19999999552965164, 10.199999995529652, 10.199999995529652),
 ('7', 0.0, 0.0, 0.0),
 ('8', 5.100000001490116, 5.100000001490116, 5.100000001490116)]

如您所见,有些值是四舍五入的,而另一些则没有。还有另一种舍入值的方法吗?

python sqlite rounding
1个回答
0
投票
[我建议将整个调用四舍五入为SUM,而不是将构成总和的单个部分四舍五入:

SELECT test_user, ROUND(SUM(CASE WHEN start >= ? THEN 24*(JULIANDAY(end) - JULIANDAY(start)) ELSE 0 END), 2) FROM test_table WHERE start < ? GROUP BY test_user;

© www.soinside.com 2019 - 2024. All rights reserved.