如何使用休眠注释将计算字段四舍五入到 n 位小数
@Format
?
@Column(name = "weight")
@Formula("round(weight/1000)")
private Double weight;
您可以将该数字乘以 10 的 n 次方,四舍五入到最接近的整数,然后再次除以 10 的 n 次方。
@Column(name = "weight")
@Formula("round(weight/1000)")
private Double weight;
n=5; //just for demonstration purposes
weight *= Math.pow(10,n); //multiplying it by 10 to the power n
Math.round(weight); //rounding it off
weight /= Math.pow(10,n); //getting the rounded off value for weight
只需使用 Java Decimalformat util 类。您应该使用该模式:###.##
如果你想四舍五入小数点后n位,那么:
String s = ".";
for(int i = 0; i<n; i++) {
s += "#";
}
if(n <= 0) {
s = "";
}
System.out.println(new DecimalFormat("###" + s).format(ur number));
不知道是否正确。如果有任何错误请纠正我。
首先,在定义
@Formula
时,使用 1000
而不是 1000.0
。我遇到了 SQL 将答案舍入为 Int 值而不使用 1000.0
的问题。
其次,您可以在使用 postgres
ROUND 函数时添加一个
n
值。
round(v 数字,s int)
round(42.4382, 2)
42.44
解决方案:
@Column(name = "weight")
@Formula("ROUND(weight/1000.0, 2)")
private Double weight;
在此示例中,
2
是您的 n
值。