This is an improvement on @jpydymond's answer, as it corrects for the problem where the internal value of sub-decimal '.xxxx5' can really be '.xxxx499999...'. That can cause his 'round(123.335,2)' to return 123.33 instead of the desired 123.34. The snippet fixes that and also constrains to the limit of 0...9 decimal places due to 64-bit precision limits.
public static double round (double value, int decimalPlaces) {
if(decimalPlaces < 0 || decimalPlaces > 9) {
throw new IllegalArgumentException("The specified decimalPlaces must be between 0 and 9 (inclusive).");
}
int scale = (int) Math.pow(10, decimalPlaces);
double scaledUp = value * scale;
double dec = scaledUp % 1d;
double fixedDec = Math.round(dec*10)/10.;
double newValue = scaledUp+fixedDec;
return (double) Math.round( newValue )/scale;
}
Sample output:
round(265.335,0) = 266.0
round(265.335,2) = 265.34
round(265.3335,3) = 265.334
round(265.3333335,6) = 265.333334
round(265.33333335,7) = 265.3333334
round(265.333333335,8) = 265.33333334
round(265.3333333335,9) = 265.333333334
round(1265.3333333335,9) = 1265.333333334
round(51265.3333333335,9) = 51265.333333334
round(251265.3333333335,9) = 251265.333333334
round(100251265.3333333335,9) = 1.0025126533333333E8
round(0.1,0) = 0.0
round(0.1,5) = 0.1
round(0.1,7) = 0.1
round(0.1,9) = 0.1
round(16.45,1) = 16.5
I hope this is helpful.