Java method to round a number to specified decimal places

Example: roundToDecimals(1.23456, 2) will return 1.23.

public static float roundToDecimals(float fl, int roundToThisManyDecimalPoints) {
	float ret = 0;
	float pow = (float) Math.pow(10, roundToThisManyDecimalPoints);
	fl = fl * pow;
	float tmpFl = Math.round(fl);
	ret = (float) tmpFl / pow;
	return ret;
}

Leave a Reply

Your email address will not be published.