Search the Site

Sponsors

bottom corner

Java method to round a number to specified decimal places

This note provides a simple method for rounding a number to a specified number of decimal places in Java.

This page is filed under keyword(s): java.

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;
}

Did you find this page useful? Please consider browsing other articles or subscribing to the RSS feed to keep up with latest.

This page is filed under keyword(s): java.
Author: C. Peter Chen
Last updated: 1 Jul 2010

bottom corner