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