The function I need:
Rounds a double to the specified number of decimal places
I figured this would be a part of java.lang.math, but inexplicably it doesn't have a round function that returns a double. Thus, my proposed solution is to add my own round function in a MathEx class.
/**
* Holds generic math functions to extend the capabilities of the java.lang.Math class
*/
public class MathEx {
/**
* Rounds a double to the specified number of decimal places using the ubiquitous "half up" rounding method
* @param numberToRound The number to be rounded
* @param numberOfDecimals The number of decimals to include in the rounded number
* @return The rounded number
*/
public static double round(double numberToRound, int numberOfDecimals) {
return new BigDecimal(numberToRound)
.setScale(numberOfDecimals, BigDecimal.ROUND_HALF_UP)
.doubleValue();
}
}
I'd appreciate feedback on the overall strategy, the Javadoc comments, and the naming conventions.
BigDecimal... I don't expect that to be a choice that the Java developers will agree with. \$\endgroup\$BigDecimalis pretty much the only option you have. If you don't need the exact precision, a version of Manny Meng's answer should suit you. \$\endgroup\$