Java BigDecimal Parse isIntegerBigDecimal(BigDecimal bd)

Here you can find the source of isIntegerBigDecimal(BigDecimal bd)

Description

Tells if a BigDecimal stores a whole number.

License

Apache License

Declaration

static public boolean isIntegerBigDecimal(BigDecimal bd) 

Method Source Code

//package com.java2s;
/*// w  w w.  j a v a2 s. com
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import java.math.BigDecimal;

public class Main {
    /**
     * Tells if a {@link BigDecimal} stores a whole number. For example, it returns {@code true} for {@code 1.0000},
     * but {@code false} for {@code 1.0001}.
     * 
     * @since 2.3.21
     */
    static public boolean isIntegerBigDecimal(BigDecimal bd) {
        // [Java 1.5] Try to utilize BigDecimal.toXxxExact methods
        return bd.scale() <= 0 // A fast check that whole numbers usually (not always) match
                || bd.setScale(0, BigDecimal.ROUND_DOWN).compareTo(bd) == 0; // This is rather slow
        // Note that `bd.signum() == 0 || bd.stripTrailingZeros().scale() <= 0` was also tried for the last
        // condition, but stripTrailingZeros was slower than setScale + compareTo.
    }
}

Related

  1. isBigDecimal(String value)
  2. isBigDecimalAssignable(String javaDataType)
  3. isBigDecimalType(Class type)
  4. isInteger(BigDecimal decimal)
  5. isInteger(BigDecimal inValue)
  6. isIntegerValue(final BigDecimal bd)
  7. parseBigDecimal(Object o, BigDecimal defaulti)
  8. parseBigDecimal(Object obj)
  9. parseBigDecimal(Object value)