001/*
002 * Licensed under the Apache License, Version 2.0 (the "License");
003 * you may not use this file except in compliance with the License.
004 * You may obtain a copy of the License at
005 *
006 *     http://www.apache.org/licenses/LICENSE-2.0
007 *
008 * Unless required by applicable law or agreed to in writing, software
009 * distributed under the License is distributed on an "AS IS" BASIS,
010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
011 * See the License for the specific language governing permissions and
012 * limitations under the License.
013 */
014package org.gbif.utils.number;
015
016import java.math.BigDecimal;
017import java.util.Objects;
018
019/**
020 * Utility class to work with BigDecimal.
021 * See DoubleVsBigDecimal test class for more details about {@link BigDecimal}
022 */
023public class BigDecimalUtils {
024
025  private BigDecimalUtils() {}
026
027  /**
028   * Convert a double to a BigDecimal.
029   *
030   * @param value non-null value to convert into a BigDecimal.
031   * @param stripTrailingZeros should the trailing zero(s) be removed? e.g. 25.0 would become 25
032   * @return instance of BigDecimal
033   */
034  public static BigDecimal fromDouble(Double value, boolean stripTrailingZeros) {
035    Objects.requireNonNull(value);
036
037    // safer to create a BigDecimal from String than Double
038    BigDecimal bd = new BigDecimal(Double.toString(value));
039    if (stripTrailingZeros) {
040      // we do not use stripTrailingZeros() simply because it plays with the scale and returns a
041      // BigDecimal
042      // that is numerically equals. see test in BigDecimalUtilsTest
043      if (bd.remainder(BigDecimal.ONE).movePointRight(bd.scale()).intValue() == 0) {
044        bd = new BigDecimal(value.intValue());
045      }
046    }
047    return bd;
048  }
049}