需求:两个整数相除,保留两位小数并四舍五入,完了转成百分比形式,即4/5=0.80=80%
1.两个整数相除:
1 2 3 4 5 | idn_dw=> select 4 / 5 ; ?column? ---------- 0 ( 1 row) |
在sql运算中,"/"意思是相除取整,这样小数部分就会被舍去。
2.用cast将被除数转成小数
1 2 3 4 5 | idn_dw=> select cast( 4 as numeric)/ 5 ; ?column? ------------------------ 0.80000000000000000000 ( 1 row) |
也可以简化:pg中"::"是转换的意思
1 2 3 4 5 | idn_dw=> select 4 ::numeric/ 5 ; ?column? ------------------------ 0.80000000000000000000 ( 1 row) |
3.四舍五入,保留两位小数
1 2 3 4 5 | idn_dw=> select round(cast( 4 as numeric)/ 5 , 2 ); round ------- 0.80 ( 1 row) |
4.放大100,转成百分比形式
1 2 3 4 5 | idn_dw=> select concat(round( 4 ::numeric/ 5 , 2 )* 100 , '%' ); concat -------- 80.00 % ( 1 row) |
但是,小数部分不需要,调整一下顺序
1 2 3 4 5 | idn_dw=> select concat(round( 4 ::numeric/ 5 * 100 ), '%' ); concat -------- 80 % ( 1 row) |
完事。
补充:使用postgresql的round()四舍五入函数报错
需求:
使用postgresql的round()四舍五入保留两位小数
报错:
1 | HINT: No function matches the given name and argument types. You might |
解决方案:
使用cast函数将需要四舍五入的值转为 numeric,转为其他的类型可能会报错
示例:
1 | round(cast(计算结果) as numeric), 2 ) |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持自学编程网。如有错误或未考虑完全的地方,望不吝赐教。
- 本文固定链接: https://zxbcw.cn/post/205091/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)