static private final BigDecimal roundToScale(BigDecimal bd, int scale, RoundingMode mode) throws RuntimeException
    {
        int lostScaleDigits = bd.scale() - scale;
        if (lostScaleDigits <= 0) {
            return bd;
        }
        if (!isRoundingEnabled()) {
            throw new RuntimeException(String.format("Decimal scale %d is greater than the maximum %d", bd.scale(), kDefaultScale));
        }
        int desiredPrecision = Math.max(1, bd.precision() - lostScaleDigits);
        MathContext mc = new MathContext(desiredPrecision, mode);
        BigDecimal nbd = bd.round(mc);
        if (nbd.scale() != scale) {
            nbd = nbd.setScale(scale);
        }
        assert(nbd.scale() == scale);
        return nbd;
    }
static private final BigDecimal roundToScale ( BigDecimal bd , int scale , RoundingMode mode ) throws RuntimeException { int lostScaleDigits = bd . scale ( ) - scale ; if ( lostScaleDigits <= 0 ) { return bd ; } if ( ! isRoundingEnabled ( ) ) { throw new RuntimeException ( String . format ( "Decimal scale %d is greater than the maximum %d" , bd . scale ( ) , kDefaultScale ) ) ; } int desiredPrecision = Math . max ( 1 , bd . precision ( ) - lostScaleDigits ) ; MathContext mc = new MathContext ( desiredPrecision , mode ) ; BigDecimal nbd = bd . round ( mc ) ; if ( nbd . scale ( ) != scale ) { nbd = nbd . setScale ( scale ) ; } assert ( nbd . scale ( ) == scale ) ; return nbd ; }
Round a BigDecimal number to a scale, given the rounding mode.
Note that the precision of the result can depend not only on its original
precision and scale and the desired scale, but also on its value.
For example, when rounding up with scale 2:<br>
9.1999 with input scale 4 and precision 5 returns 9.20 with precision 3 (down 2).<br>
9.9999 with input scale 4 and precision 5 returns 10.00 with precision 4 (down 1).<br>
91.9999 with input scale 4 and precision 6 returns 92.00 with precision 4 (down 2).
@param bd the input value of arbitrary scale and precision
@param scale the desired scale of the return value
@param mode the rounding algorithm to use
@return the rounded value approximately equal to bd, but having the desired scale