001package org.gbif.utils.number;
002
003import java.math.BigDecimal;
004
005import com.google.common.base.Preconditions;
006
007/**
008 * Utility class to work with BigDecimal.
009 * See DoubleVsBigDecimal test class for more details about {@link BigDecimal}
010 */
011public class BigDecimalUtils {
012
013  private BigDecimalUtils(){}
014
015  /**
016   * Convert a double to a BigDecimal.
017   *
018   * @param value non-null value to convert into a BigDecimal.
019   * @param stripTrailingZeros should the trailing zero(s) be removed? e.g. 25.0 would become 25
020   * @return instance of BigDecimal
021   */
022  public static BigDecimal fromDouble(Double value, boolean stripTrailingZeros){
023
024    Preconditions.checkNotNull(value);
025
026    //safer to create a BigDecimal from String than Double
027    BigDecimal bd = new BigDecimal(Double.toString(value));
028    if(stripTrailingZeros){
029      //we do not use stripTrailingZeros() simply because it plays with the scale and returns a BigDecimal
030      //that is numerically equals. see test in BigDecimalUtilsTest
031      if(bd.remainder(BigDecimal.ONE).movePointRight(bd.scale()).intValue() == 0 ){
032        bd = new BigDecimal(value.intValue());
033      }
034    }
035    return bd;
036  }
037
038}