What is the simplest and most efficient way to find out if a given BigDecimal object is integral (4, 345.000) or fractional (4.35, 234234.5634) ?

Doug Bell

The only quick way to check for an integral BigDecimal is BigDecimal.scale() == 0. This check is quick, and if true, the BigDecimal has no fractional part. However, if false, the fractional part may still be zero (e.g. 10.0). So testing BigDecimal.scale() only tells you if there is a fractional part, but not whether the fractional part is zero.

The underlying representation for a BigDecimal is a BigInteger, which is backed by a binary representation, so there is no quick and dirty means to determine if the fractional part is zero. Therefore, the "most efficient" (approximately) means to determine if the fractional part is zero is the following method (JDK 1.2 version):

private static final BigInteger bi10 = BigInteger.valueOf(10);

boolean isIntegral (BigDecimal n)
    int scale = n.scale();

    // test for empty fractional part
    if (scale == 0)
        return true;

    BigInteger ni = n.unscaledValue();  // JDK 1.2

    // test for n == 0
    if (ni.signum() == 0)
        return true;

    // check if evenly divisible by 10^scale
    BigInteger pot = (scale == 1) ? bi10 : bi10.pow(scale);
    return ni.mod(pot).signum() == 0;

0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.