Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Fast scaling of double values?

416044Aug 3 2006 — edited Nov 2 2007
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?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 30 2007
Added on Aug 3 2006
79 comments
968 views