需求:兩個整數(shù)相除,保留兩位小數(shù)并四舍五入,完了轉(zhuǎn)成百分比形式,即4/5=0.80=80%
idn_dw=> select 4/5; ?column? ---------- 0 (1 row)
在sql運算中,"/"意思是相除取整,這樣小數(shù)部分就會被舍去。
idn_dw=> select cast(4 as numeric)/5; ?column? ------------------------ 0.80000000000000000000 (1 row)
也可以簡化:pg中"::"是轉(zhuǎn)換的意思
idn_dw=> select 4::numeric/5; ?column? ------------------------ 0.80000000000000000000 (1 row)
idn_dw=> select round(cast(4 as numeric)/5,2); round ------- 0.80 (1 row)
idn_dw=> select concat(round(4::numeric/5,2)*100,'%'); concat -------- 80.00% (1 row)
但是,小數(shù)部分不需要,調(diào)整一下順序
idn_dw=> select concat(round(4::numeric/5*100),'%'); concat -------- 80% (1 row)
完事。
補充:使用postgresql的round()四舍五入函數(shù)報錯
使用postgresql的round()四舍五入保留兩位小數(shù)
報錯:
HINT: No function matches the given name and argument types. You might
使用cast函數(shù)將需要四舍五入的值轉(zhuǎn)為 numeric,轉(zhuǎn)為其他的類型可能會報錯
示例:
round(cast(計算結(jié)果) as numeric), 2)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
標(biāo)簽:濮陽 海西 榆林 辛集 溫州 昭通 寶雞 杭州
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《PostGresql 實現(xiàn)四舍五入、小數(shù)轉(zhuǎn)換、百分比的用法說明》,本文關(guān)鍵詞 PostGresql,實現(xiàn),四舍五入,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。