How do you round to n decimal places a calculated field using hibernate annotation @Format
?
@Column(name = "weight")
@Formula("round(weight/1000)")
private Double weight;
CodePudding user response:
Just use Java Decimalformat util class. You should use that pattern: ###.##
If you want to round n decimal places then do:
String s = ".";
for(int i = 0; i<n; i ) {
s = "#";
}
if(n <= 0) {
s = "";
}
System.out.println(new DecimalFormat("###" s).format(ur number));
idk if it's right. If a made any misteak then correct me.
CodePudding user response:
You could multiply the number with 10 to the power n, round it off to the nearest whole number and then divide it with 10 to the power n again.
@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