服务器之家

服务器之家 > 正文

PostGresql 实现四舍五入、小数转换、百分比的用法说明

时间:2021-04-09 18:08     来源/作者:仙道Bob

需求:两个整数相除,保留两位小数并四舍五入,完了转成百分比形式,即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://blog.csdn.net/jsbylibo/article/details/102801221

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部