So far, I use my own method to scale double values:
/**
* Scale decimal number via the rounding mode BigDecimal.ROUND_HALF_UP.
*
* @param value Decimal value.
* @param scale New scale.
* @param roundingMode Optional rounding mode from BigDecimal.ROUND_... constants. (Default: BigDecimal.ROUND_HALF_UP)
* @return Scaled number.
* @since 1.8.3
*/
static public double getScaled(double value, final int scale, final int... roundingMode) {
double result = value; //default: unscaled
value = (Double.isNaN(value) || Double.isInfinite(value)) ? 0.0 : value; //reser NaN
//use BigDecimal String constructor as this is the only exact way for double values
int rm = BigDecimal.ROUND_HALF_UP;
if (roundingMode != null && roundingMode.length > 0) {
rm = roundingMode[0];
}
result = new BigDecimal(""+value).setScale(scale, rm).doubleValue();
return result;
}//getScaled()
BigDecimal offers scale methods, so I use them. The String constructor is also the only way to convert a double into a BigDecimal.
This works fine but is quite slow on heavy number crunching with lots of scales. Is there a faster way?