Round to 2 decimal places in hibernate query language

此生再无相见时 提交于 2019-12-06 06:26:56

I have struggled with this a lot an finally found the following solution:

If you want to be more DB independent and specifically want to support Postgres or Oracle DB you can use the floor function for rounding which is pretty generic and does not leave much room for different implementations, meaning this will probably work with all databases (tested with Postgres and MySQL).

The snippet performs rounding to 2 digits and rounds by the absolute value. You can easily adapt this to your needs.

Regard the division by 100 using 100.0. This will insure that you always get a double as a result which is particularly important if you build a sum over the rounded values.

floor(abs(value) * 100 + 0.5)/100.0 * sign(value)

use FORMAT function on property to 2 decimal point

Select FORMAT(p.amount,2) as amt,p.desc from pay p, register r where r.type=?1 and r.code=?2;

alternatively you can specify the same in mapping file as well like below

 <property name="amount">
        <column name="amount" scale="15" precision="3" sql-type="number(15,2)"/>
    </property>

This worked for me

cast(value as decimal(9,2))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!