Java – the fastest way to round to three decimal places

java

The SO community was right, profiling your code before you ask performance questions seems to make more sense then my approach of randomly guessing 🙂 I profiled my code(very intensive math) and didn't realize over 70% of my code is apparently in a part I didn't think was a source of slowdown, rounding of decimals.

static double roundTwoDecimals(double d) {
    DecimalFormat twoDForm = new DecimalFormat("#.###");
    return Double.valueOf(twoDForm.format(d));
}

My problem is I get decimal numbers that are normally .01,.02,etc..but sometimes I get something like .070000000001 (I really only care about the 0.07 but floating point precision causes my other formulas that result to fail), I simply want the first 3 decimals to avoid this problem.

So is there a better/faster way to do this?

Best Answer

The standard way to round (positive) numbers would be something like this:

double rounded = floor(1000 * doubleVal + 0.5) / 1000;

Example 1: floor(1000 * .1234 + 0.5) / 1000 = floor(123.9)/1000 = 0.123
Example 2: floor(1000 * .5678 + 0.5) / 1000 = floor(568.3)/1000 = 0.568

But as @nuakh commented, you'll always be plagued by rounding errors to some extent. If you want exactly 3 decimal places, your best bet is to convert to thousandths (that is, multiply everything by 1000) and use an integral data type (int, long, etc.)

In that case, you'd skip the final division by 1000 and use the integral values 123 and 568 for your calculations. If you want the results in the form of percentages, you'd divide by 10 for display:

123 → 12.3%
568 → 56.8%