简体   繁体   中英

Scaling issue in BigDecimal(java) for exponential notation

In our application, we need to check whether the given number is in range or not and for this we are using below code -

 boolean isValidRangeNumber(Double no,int precision, int scale){
            BigDecimal bigDecimal = new BigDecimal(no.toString());
            int intPartLength = precision - scale;
            int size = (bigDecimal.longValue() + "").toString().length();

            if(bigDecimal.precision() <= precision && bigDecimal.scale() <= scale && size <= intPartLength)
                return true;

            return false;
        }

But when we are calling isValidRangeNumber(0.0000009, 10,7) than its failing as bigDecimal.scale() is giving 8 which can be max 7 whereas its a valid number. Please suggest, what is wrong with this BigDecimal usage.

If you inspect following :

bigDecimal.toPlainString() // This will show 0.00000090 -> scale of 8, appends trailing 0

Because of an extra trailing zero, following condition evaluates to false.

bigDecimal.scale() <= scale // 8 <= 7

You can change into following :

boolean isValidRangeNumber(Double no, int precision, int scale) {
    BigDecimal bigDecimal = new BigDecimal(no.toString()).stripTrailingZeros(); //Get rid of trailing zeros
    bigDecimal.toPlainString();
    int intPartLength = precision - scale;

    int size = (bigDecimal.longValue() + "").toString().length();

    if (bigDecimal.precision() <= precision && bigDecimal.scale() <= scale
            && size <= intPartLength)
        return true;

    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM