英文:
Preventing integer division by casting one of the operands as non-integer
问题
需要将分子和分母都强制转换为非整数数据类型以防止整数除法吗?
英文:
Do I have to cast both the numerator and the denominator to a non-integer data type to prevent integer division?
答案1
得分: 0
只需要将一个操作数(要么分子,要么分母)进行类型转换,以防止整数除法,正如手册所述。无需同时进行两者的类型转换:
select 2 / 4; -- 0
select 2::numeric / 4; -- 0.50000000000000000000
select 2 / 4::numeric; -- 0.50000000000000000000
select 2::numeric / 4::numeric; -- 0.50000000000000000000
另请参阅:
这些示例中有2次类型转换,而只需要1次类型转换:
英文:
It is enough to cast one of the operands (either the numerator or the denominator) to prevent integer division, as the manual says. Casting both is not necessary:
select 2 / 4; -- 0
select 2::numeric / 4; -- 0.50000000000000000000
select 2 / 4::numeric; -- 0.50000000000000000000
select 2::numeric / 4::numeric; -- 0.50000000000000000000
SEE ALSO:
- PostgreSQL manual: Numeric Types
- PostgreSQL manual: Mathematical Functions and Operators
- https://stackoverflow.com/q/55537600/967621
These have 2 casts, while only 1 cast is needed:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论