Example usage for java.math BigDecimal scale

List of usage examples for java.math BigDecimal scale

Introduction

In this page you can find the example usage for java.math BigDecimal scale.

Prototype

int scale

To view the source code for java.math BigDecimal scale.

Click Source Link

Document

The scale of this BigDecimal, as returned by #scale .

Usage

From source file:org.kuali.rice.core.api.util.type.AbstractKualiDecimal.java

/**
 * Wraps BigDecimal's subtract method to accept and return T instances
 * instead of BigDecimals, so that users of the class don't have to typecast
 * the return value.//from w  w w  . j  a  v  a2s.c  om
 * 
 * @param subtrahend
 * @return result of the subtracting the given subtrahend from this value
 * @throws IllegalArgumentException
 *             if the given subtrahend is null
 */
public T subtract(T subtrahend) {
    if (subtrahend == null) {
        throw new IllegalArgumentException("invalid (null) subtrahend");
    }

    BigDecimal difference = this.value.subtract(subtrahend.value);
    return newInstance(difference, difference.scale());
}

From source file:org.talend.dataprep.transformation.actions.math.TemperaturesConverter.java

@Override
protected String calculateResult(String columnValue, ActionContext context) {
    TemperatureUnit fromTemperatureUnit = TemperatureUnit
            .valueOf(context.getParameters().get(FROM_UNIT_PARAMETER));
    TemperatureUnit toTemperatureUnit = TemperatureUnit.valueOf(context.getParameters().get(TO_UNIT_PARAMETER));
    String precisionParameter = context.getParameters().get(TARGET_PRECISION);

    BigDecimal value = BigDecimalParser.toBigDecimal(columnValue);
    TemperatureImpl fromTemp = new TemperatureImpl(value, fromTemperatureUnit.asJavaUnit());
    TemperatureImpl temperature = fromTemp.convertTo(toTemperatureUnit.asJavaUnit());

    // Precision is used as scale, for precision as significant digits, see history
    Integer targetScale = NumberUtils.toInt(precisionParameter, value.scale());

    return temperature.getValue().setScale(targetScale, RoundingMode.HALF_UP).toPlainString();
}

From source file:org.kuali.rice.core.api.util.type.AbstractKualiDecimal.java

/**
 * Overloaded multiply method where we can specify if we need to preserve the precision of the result
 * // www . j  ava 2  s.c  o  m
 * @param multiplicand
 * @param applyScale
 * @return result of multiplying this value by the given multiplier
 * @throws IllegalArgumentException
 *             if the given multiplier is null
 */
public T multiply(T multiplier, boolean applyScale) {
    if (multiplier == null) {
        throw new IllegalArgumentException("invalid (null) multiplier");
    }

    BigDecimal product = this.value.multiply(multiplier.value);
    return newInstance(product, applyScale ? this.value.scale() : product.scale());
}

From source file:org.kuali.rice.core.api.util.type.AbstractKualiDecimal.java

public T divide(T divisor, boolean applyScale) {
    if (divisor == null) {
        throw new IllegalArgumentException("invalid (null) divisor");
    }/*from   www  .  j a  v a 2 s .  c  o  m*/
    BigDecimal quotient = this.value.divide(divisor.value, ROUND_BEHAVIOR);

    T result = newInstance(quotient, applyScale ? this.value.scale() : quotient.scale());
    return result;
}

From source file:org.openhab.persistence.influxdb.internal.InfluxDBPersistenceService.java

/**
 * This method returns an integer if possible if not a double is returned. This is an optimization
 * for influxdb because integers have less overhead.
 * /*  w  w w. j a  va2  s . c  o m*/
 * @param value the BigDecimal to be converted
 * @return A double if possible else a double is returned.
 */
private Object convertBigDecimalToNum(BigDecimal value) {
    Object convertedValue;
    if (value.scale() == 0) {
        logger.trace("found no fractional part");
        convertedValue = value.toBigInteger();
    } else {
        logger.trace("found fractional part");
        convertedValue = value.doubleValue();
    }
    return convertedValue;
}

From source file:org.kuali.kfs.module.purap.businessobject.PurApItemBase.java

@Override
public void setItemUnitPrice(BigDecimal itemUnitPrice) {
    if (itemUnitPrice != null) {
        if (itemUnitPrice.scale() < PurapConstants.DOLLAR_AMOUNT_MIN_SCALE) {
            itemUnitPrice = itemUnitPrice.setScale(PurapConstants.DOLLAR_AMOUNT_MIN_SCALE,
                    KualiDecimal.ROUND_BEHAVIOR);
        } else if (itemUnitPrice.scale() > PurapConstants.UNIT_PRICE_MAX_SCALE) {
            itemUnitPrice = itemUnitPrice.setScale(PurapConstants.UNIT_PRICE_MAX_SCALE,
                    KualiDecimal.ROUND_BEHAVIOR);
        }//from  w  w w . ja v a 2s. c  om
    }
    this.itemUnitPrice = itemUnitPrice;
}

From source file:org.marketcetera.trade.Option.java

/**
 * Constructor. Note that trailing zeros are stripped from strikePrice.
 * //ww  w .j  a  v a  2  s. c o  m
 * @param symbol
 *            the option root symbol
 * @param expiry
 *            the option expiry
 * @param strikePrice
 *            the option strike price
 * @param type
 *            the option type
 * @throws IllegalArgumentException
 *             if any argument is null, or if symbol or expiry is whitespace
 */
public Option(String symbol, String expiry, BigDecimal strikePrice, OptionType type) {
    symbol = StringUtils.trimToNull(symbol);
    expiry = StringUtils.trimToNull(expiry);
    Validate.notNull(symbol);
    Validate.notNull(type);
    Validate.notNull(expiry);
    Validate.notNull(strikePrice);
    mSymbol = symbol;
    mType = type;
    mExpiry = expiry;
    mAugmentedExpiry = OptionUtils.normalizeEquityOptionExpiry(mExpiry);
    strikePrice = strikePrice.stripTrailingZeros();
    if (strikePrice.scale() < 0) {
        //reset the scale if the number is a multiple of 10
        strikePrice = strikePrice.setScale(0);
    }
    mStrikePrice = strikePrice;
}

From source file:org.apache.hadoop.hive.ql.exec.ColumnStatsUpdateTask.java

private ColumnStatistics constructColumnStatsFromInput() throws SemanticException, MetaException {

    String dbName = SessionState.get().getCurrentDatabase();
    ColumnStatsDesc desc = work.getColStats();
    String tableName = desc.getTableName();
    String partName = work.getPartName();
    List<String> colName = desc.getColName();
    List<String> colType = desc.getColType();

    ColumnStatisticsObj statsObj = new ColumnStatisticsObj();

    // grammar prohibits more than 1 column so we are guaranteed to have only 1
    // element in this lists.

    statsObj.setColName(colName.get(0));

    statsObj.setColType(colType.get(0));

    ColumnStatisticsData statsData = new ColumnStatisticsData();

    String columnType = colType.get(0);

    if (columnType.equalsIgnoreCase("long")) {
        LongColumnStatsData longStats = new LongColumnStatsData();
        longStats.setNumNullsIsSet(false);
        longStats.setNumDVsIsSet(false);
        longStats.setLowValueIsSet(false);
        longStats.setHighValueIsSet(false);
        Map<String, String> mapProp = work.getMapProp();
        for (Entry<String, String> entry : mapProp.entrySet()) {
            String fName = entry.getKey();
            String value = entry.getValue();
            if (fName.equals("numNulls")) {
                longStats.setNumNulls(Long.parseLong(value));
            } else if (fName.equals("numDVs")) {
                longStats.setNumDVs(Long.parseLong(value));
            } else if (fName.equals("lowValue")) {
                longStats.setLowValue(Long.parseLong(value));
            } else if (fName.equals("highValue")) {
                longStats.setHighValue(Long.parseLong(value));
            } else {
                throw new SemanticException("Unknown stat");
            }//from  w  ww .  j  ava2 s . co m

        }
        statsData.setLongStats(longStats);
        statsObj.setStatsData(statsData);
    } else if (columnType.equalsIgnoreCase("double")) {
        DoubleColumnStatsData doubleStats = new DoubleColumnStatsData();
        doubleStats.setNumNullsIsSet(false);
        doubleStats.setNumDVsIsSet(false);
        doubleStats.setLowValueIsSet(false);
        doubleStats.setHighValueIsSet(false);
        Map<String, String> mapProp = work.getMapProp();
        for (Entry<String, String> entry : mapProp.entrySet()) {
            String fName = entry.getKey();
            String value = entry.getValue();
            if (fName.equals("numNulls")) {
                doubleStats.setNumNulls(Long.parseLong(value));
            } else if (fName.equals("numDVs")) {
                doubleStats.setNumDVs(Long.parseLong(value));
            } else if (fName.equals("lowValue")) {
                doubleStats.setLowValue(Double.parseDouble(value));
            } else if (fName.equals("highValue")) {
                doubleStats.setHighValue(Double.parseDouble(value));
            } else {
                throw new SemanticException("Unknown stat");
            }
        }
        statsData.setDoubleStats(doubleStats);
        statsObj.setStatsData(statsData);
    } else if (columnType.equalsIgnoreCase("string")) {
        StringColumnStatsData stringStats = new StringColumnStatsData();
        stringStats.setMaxColLenIsSet(false);
        stringStats.setAvgColLenIsSet(false);
        stringStats.setNumNullsIsSet(false);
        stringStats.setNumDVsIsSet(false);
        Map<String, String> mapProp = work.getMapProp();
        for (Entry<String, String> entry : mapProp.entrySet()) {
            String fName = entry.getKey();
            String value = entry.getValue();
            if (fName.equals("numNulls")) {
                stringStats.setNumNulls(Long.parseLong(value));
            } else if (fName.equals("numDVs")) {
                stringStats.setNumDVs(Long.parseLong(value));
            } else if (fName.equals("avgColLen")) {
                stringStats.setAvgColLen(Double.parseDouble(value));
            } else if (fName.equals("maxColLen")) {
                stringStats.setMaxColLen(Long.parseLong(value));
            } else {
                throw new SemanticException("Unknown stat");
            }
        }
        statsData.setStringStats(stringStats);
        statsObj.setStatsData(statsData);
    } else if (columnType.equalsIgnoreCase("boolean")) {
        BooleanColumnStatsData booleanStats = new BooleanColumnStatsData();
        booleanStats.setNumNullsIsSet(false);
        booleanStats.setNumTruesIsSet(false);
        booleanStats.setNumFalsesIsSet(false);
        Map<String, String> mapProp = work.getMapProp();
        for (Entry<String, String> entry : mapProp.entrySet()) {
            String fName = entry.getKey();
            String value = entry.getValue();
            if (fName.equals("numNulls")) {
                booleanStats.setNumNulls(Long.parseLong(value));
            } else if (fName.equals("numTrues")) {
                booleanStats.setNumTrues(Long.parseLong(value));
            } else if (fName.equals("numFalses")) {
                booleanStats.setNumFalses(Long.parseLong(value));
            } else {
                throw new SemanticException("Unknown stat");
            }
        }
        statsData.setBooleanStats(booleanStats);
        statsObj.setStatsData(statsData);
    } else if (columnType.equalsIgnoreCase("binary")) {
        BinaryColumnStatsData binaryStats = new BinaryColumnStatsData();
        binaryStats.setNumNullsIsSet(false);
        binaryStats.setAvgColLenIsSet(false);
        binaryStats.setMaxColLenIsSet(false);
        Map<String, String> mapProp = work.getMapProp();
        for (Entry<String, String> entry : mapProp.entrySet()) {
            String fName = entry.getKey();
            String value = entry.getValue();
            if (fName.equals("numNulls")) {
                binaryStats.setNumNulls(Long.parseLong(value));
            } else if (fName.equals("avgColLen")) {
                binaryStats.setAvgColLen(Double.parseDouble(value));
            } else if (fName.equals("maxColLen")) {
                binaryStats.setMaxColLen(Long.parseLong(value));
            } else {
                throw new SemanticException("Unknown stat");
            }
        }
        statsData.setBinaryStats(binaryStats);
        statsObj.setStatsData(statsData);
    } else if (columnType.equalsIgnoreCase("decimal")) {
        DecimalColumnStatsData decimalStats = new DecimalColumnStatsData();
        decimalStats.setNumNullsIsSet(false);
        decimalStats.setNumDVsIsSet(false);
        decimalStats.setLowValueIsSet(false);
        decimalStats.setHighValueIsSet(false);
        Map<String, String> mapProp = work.getMapProp();
        for (Entry<String, String> entry : mapProp.entrySet()) {
            String fName = entry.getKey();
            String value = entry.getValue();
            if (fName.equals("numNulls")) {
                decimalStats.setNumNulls(Long.parseLong(value));
            } else if (fName.equals("numDVs")) {
                decimalStats.setNumDVs(Long.parseLong(value));
            } else if (fName.equals("lowValue")) {
                BigDecimal d = new BigDecimal(value);
                decimalStats.setLowValue(
                        new Decimal(ByteBuffer.wrap(d.unscaledValue().toByteArray()), (short) d.scale()));
            } else if (fName.equals("highValue")) {
                BigDecimal d = new BigDecimal(value);
                decimalStats.setHighValue(
                        new Decimal(ByteBuffer.wrap(d.unscaledValue().toByteArray()), (short) d.scale()));
            } else {
                throw new SemanticException("Unknown stat");
            }
        }
        statsData.setDecimalStats(decimalStats);
        statsObj.setStatsData(statsData);
    } else if (columnType.equalsIgnoreCase("date")) {
        DateColumnStatsData dateStats = new DateColumnStatsData();
        Map<String, String> mapProp = work.getMapProp();
        for (Entry<String, String> entry : mapProp.entrySet()) {
            String fName = entry.getKey();
            String value = entry.getValue();
            if (fName.equals("numNulls")) {
                dateStats.setNumNulls(Long.parseLong(value));
            } else if (fName.equals("numDVs")) {
                dateStats.setNumDVs(Long.parseLong(value));
            } else if (fName.equals("lowValue")) {
                // Date high/low value is stored as long in stats DB, but allow users to set high/low
                // value using either date format (yyyy-mm-dd) or numeric format (days since epoch)
                dateStats.setLowValue(readDateValue(value));
            } else if (fName.equals("highValue")) {
                dateStats.setHighValue(readDateValue(value));
            } else {
                throw new SemanticException("Unknown stat");
            }
        }
        statsData.setDateStats(dateStats);
        statsObj.setStatsData(statsData);
    } else {
        throw new SemanticException("Unsupported type");
    }
    String[] names = Utilities.getDbTableName(dbName, tableName);
    ColumnStatisticsDesc statsDesc = getColumnStatsDesc(names[0], names[1], partName, partName == null);
    ColumnStatistics colStat = new ColumnStatistics();
    colStat.setStatsDesc(statsDesc);
    colStat.addToStatsObj(statsObj);
    return colStat;
}

From source file:org.ojai.json.impl.JsonStreamDocumentReader.java

@Override
public int getDecimalScale() {
    BigDecimal decimal = getDecimal();
    if (decimal != null) {
        return decimal.scale();
    }/*from  w w w .j a v  a2s.c o  m*/
    return 0;
}

From source file:it.newfammulfin.api.EntryResource.java

private <K> boolean checkAndBalanceZeroShares(final Map<K, BigDecimal> shares, BigDecimal expectedSum) {
    if (shares.isEmpty()) {
        return false;
    }//from   w  w  w .  ja  va  2  s.co  m
    boolean equalShares = false;
    if (!Util.containsNotZero(shares.values())) {
        equalShares = true;
        expectedSum = expectedSum.setScale(Math.max(DEFAULT_SHARE_SCALE, expectedSum.scale()));
        for (Map.Entry<K, BigDecimal> shareEntry : shares.entrySet()) {
            shareEntry.setValue(expectedSum.divide(BigDecimal.valueOf(shares.size()), RoundingMode.DOWN));
        }
    }
    K largestKey = shares.keySet().iterator().next();
    for (Map.Entry<K, BigDecimal> share : shares.entrySet()) {
        if (share.getValue().abs().compareTo(shares.get(largestKey).abs()) > 0) {
            largestKey = share.getKey();
        }
    }
    BigDecimal remainder = Util.remainder(shares.values(), expectedSum);
    if (remainder.compareTo(BigDecimal.ZERO) != 0) {
        shares.put(largestKey, shares.get(largestKey).add(remainder));
    }
    return equalShares;
}