Example usage for java.math BigDecimal setScale

List of usage examples for java.math BigDecimal setScale

Introduction

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

Prototype

public BigDecimal setScale(int newScale) 

Source Link

Document

Returns a BigDecimal whose scale is the specified value, and whose value is numerically equal to this BigDecimal 's.

Usage

From source file:dk.clanie.bitcoin.client.BitcoindClientImpl.java

/**
 * Sends the given amount to the given address, ensuring the account has a
 * valid balance using <code>minconf</code> confirmations. Returns the
 * transaction id if successful./*from   w  ww  .  j a  v a2s  .c o  m*/
 * <p>
 * Requires unlocked wallet.
 * 
 * @param account
 * @param address
 *            - recipient's bitcoin address
 * @param amount
 *            - bitcoins
 * @param minConf
 *            - optional (may be null). Minimum number of confirmations for
 *            consumed transaction outputs. Default 1.
 * @param comment
 *            - optional (may be null). Text for the transactions comment
 *            field
 * @param commentTo
 *            - optional (may be null). Text for the transactions to: field
 * @return String with transaction number
 */
@Override
public StringResponse sendFrom(String account, String address, BigDecimal amount, Integer minConf,
        String comment, String commentTo) {
    List<Object> params = newArrayList();
    params.add(account);
    params.add(address);
    params.add(amount.setScale(SCALE));
    params.add(firstNotNull(minConf, 1));
    if (comment != null || commentTo != null)
        params.add(comment);
    if (commentTo != null)
        params.add(commentTo);
    return jsonRpc("sendfrom", params, StringResponse.class);
}

From source file:com.healthmarketscience.jackcess.Column.java

/**
 * Writes "Currency" values.//from  ww  w . ja  v  a  2 s . c o m
 */
private static void writeCurrencyValue(ByteBuffer buffer, Object value) throws IOException {
    Object inValue = value;
    try {
        BigDecimal decVal = toBigDecimal(value);
        inValue = decVal;

        // adjust scale (will cause the an ArithmeticException if number has too
        // many decimal places)
        decVal = decVal.setScale(4);

        // now, remove scale and convert to long (this will throw if the value is
        // too big)
        buffer.putLong(decVal.movePointRight(4).longValueExact());
    } catch (ArithmeticException e) {
        throw (IOException) new IOException("Currency value '" + inValue + "' out of range").initCause(e);
    }
}

From source file:org.libreplan.web.orders.ManageOrderElementAdvancesModel.java

@Override
public BigDecimal getPercentageAdvanceMeasurement(AdvanceMeasurement advanceMeasurement) {
    AdvanceAssignment assignment = advanceMeasurement.getAdvanceAssignment();
    if (assignment == null) {
        return BigDecimal.ZERO;
    }/*ww w.  jav a 2 s .  c  om*/

    BigDecimal maxValue;
    if (assignment instanceof IndirectAdvanceAssignment) {

        maxValue = orderElement.calculateFakeDirectAdvanceAssignment((IndirectAdvanceAssignment) assignment)
                .getMaxValue();
    } else {
        maxValue = ((DirectAdvanceAssignment) assignment).getMaxValue();
    }

    if (maxValue.compareTo(BigDecimal.ZERO) <= 0) {
        return BigDecimal.ZERO;
    }

    BigDecimal value = advanceMeasurement.getValue();
    if (value == null) {
        return BigDecimal.ZERO;
    }

    BigDecimal division = value.divide(maxValue.setScale(2), 4, RoundingMode.DOWN);
    return (division.multiply(new BigDecimal(100))).setScale(2, RoundingMode.DOWN);

}

From source file:org.efaps.esjp.accounting.transaction.FieldUpdate_Base.java

/**
 * Executed on update event of the currency field.
 * @param _parameter    parameter as passed from the eFaps API
 * @return  list of maps as needed by the update event
 * @throws EFapsException on error//from   w  w w .j a  v  a  2s .  c o m
 */
public Return update4Currency(final Parameter _parameter) throws EFapsException {
    final Return ret = new Return();
    try {
        final String postfix = getProperty(_parameter, "TypePostfix");

        final String[] currIds = _parameter.getParameterValues("rateCurrencyLink_" + postfix);
        final String[] amounts = _parameter.getParameterValues("amount_" + postfix);

        final int pos = getSelectedRow(_parameter);

        final ExchangeConfig exConf = getExchangeConfig(_parameter, null);
        final DateTime date;
        switch (exConf) {
        case DOCDATEPURCHASE:
        case DOCDATESALE:
            final Instance docInst = Instance.get(_parameter.getParameterValues("docLink_" + postfix)[pos]);
            if (InstanceUtils.isValid(docInst)) {
                final PrintQuery print = CachedPrintQuery.get4Request(docInst);
                print.addAttribute(CIERP.DocumentAbstract.Date);
                print.execute();
                date = print.getAttribute(CIERP.DocumentAbstract.Date);
            } else {
                final String dateStr = _parameter.getParameterValue("date_eFapsDate");
                date = DateUtil.getDateFromParameter(dateStr);
            }
            break;
        case TRANSDATESALE:
        case TRANSDATEPURCHASE:
        default:
            final String dateStr = _parameter.getParameterValue("date_eFapsDate");
            date = DateUtil.getDateFromParameter(dateStr);
            break;
        }

        final boolean sale = ExchangeConfig.TRANSDATESALE.equals(exConf)
                || ExchangeConfig.DOCDATESALE.equals(exConf);

        final Instance periodInstance = new Period().evaluateCurrentPeriod(_parameter);
        final RateInfo rate = evaluateRate(_parameter, periodInstance, date,
                Instance.get(CIERP.Currency.getType(), currIds[pos]));
        final DecimalFormat rateFormater = sale ? rate.getFormatter().getFrmt4SaleRateUI()
                : rate.getFormatter().getFrmt4RateUI();
        final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter();
        final BigDecimal amountRate = amounts[pos].isEmpty() ? BigDecimal.ZERO
                : (BigDecimal) rateFormater.parse(amounts[pos]);

        final BigDecimal sum = getSum4UI(_parameter, postfix, pos, rate);
        final String postfix2 = "Debit".equals(postfix) ? "Credit" : "Debit";
        final BigDecimal sum2 = getSum4UI(_parameter, postfix2, null, null);
        final String sumStr = formater.format(sum) + " " + new Period().getCurrency(periodInstance).getSymbol();
        final String sumStr2 = formater.format(sum.subtract(sum2).abs()) + " "
                + new Period().getCurrency(periodInstance).getSymbol();

        final List<Map<String, String>> list = new ArrayList<>();
        final Map<String, String> map = new HashMap<>();
        map.put("rate_" + postfix, sale ? rate.getSaleRateUIFrmt() : rate.getRateUIFrmt());
        map.put("rate_" + postfix + RateUI.INVERTEDSUFFIX, "" + rate.isInvert());
        map.put("sum" + postfix, sumStr);
        map.put("amountRate_" + postfix, formater.format(amountRate.setScale(12)
                .divide(sale ? rate.getSaleRate() : rate.getRate(), BigDecimal.ROUND_HALF_UP)));
        map.put("sumTotal", sumStr2);
        list.add(map);
        ret.put(ReturnValues.VALUES, list);
    } catch (final ParseException e) {
        throw new EFapsException(Transaction_Base.class, "update4Currency.ParseException", e);
    }
    return ret;
}

From source file:org.efaps.esjp.accounting.transaction.FieldUpdate_Base.java

/**
 * Method is executed on update trigger for the amount field in the debit
 * and credit table inside the transaction form.
 *
 * @param _parameter Parameter as passed from the eFaps API
 * @return list for update trigger//w w w.j  a  va2 s . com
 * @throws EFapsException on error
 */
public Return update4Amount(final Parameter _parameter) throws EFapsException {
    final Return retVal = new Return();
    try {
        final String postfix = getProperty(_parameter, "TypePostfix");
        final String[] amounts = _parameter.getParameterValues("amount_" + postfix);
        final String[] rates = _parameter.getParameterValues("rate_" + postfix);
        final String[] ratesInv = _parameter.getParameterValues("rate_" + postfix + RateUI.INVERTEDSUFFIX);

        final int pos = getSelectedRow(_parameter);
        final DecimalFormat rateFormater = NumberFormatter.get().getFormatter(0, 8);
        final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter();
        final BigDecimal amount = amounts[pos].isEmpty() ? BigDecimal.ZERO
                : (BigDecimal) rateFormater.parse(amounts[pos]);
        BigDecimal rate = rates[pos].isEmpty() ? BigDecimal.ZERO : (BigDecimal) rateFormater.parse(rates[pos]);
        final boolean rateInv = "true".equalsIgnoreCase(ratesInv[pos]);
        if (rateInv && rate.compareTo(BigDecimal.ZERO) != 0) {
            rate = BigDecimal.ONE.divide(rate, 12, BigDecimal.ROUND_HALF_UP);
        }
        final List<Map<String, String>> list = new ArrayList<>();
        final Instance periodInstance = new Period().evaluateCurrentPeriod(_parameter);

        final BigDecimal sum = getSum4UI(_parameter, postfix, null, null);
        final String postfix2 = "Debit".equals(postfix) ? "Credit" : "Debit";
        final BigDecimal sum2 = getSum4UI(_parameter, postfix2, null, null);
        final String sumStr = formater.format(sum) + " " + new Period().getCurrency(periodInstance).getSymbol();
        final String sumStr2 = formater.format(sum.subtract(sum2).abs()) + " "
                + new Period().getCurrency(periodInstance).getSymbol();

        final Map<String, String> map = new HashMap<>();
        map.put("sum" + postfix, sumStr);
        map.put("amountRate_" + postfix,
                formater.format(amount.setScale(8).divide(rate, BigDecimal.ROUND_HALF_UP)));
        map.put("sumTotal", sumStr2);
        list.add(map);
        retVal.put(ReturnValues.VALUES, list);
    } catch (final ParseException e) {
        throw new EFapsException(Transaction_Base.class, "update4Amount.ParseException", e);
    }
    return retVal;
}

From source file:org.efaps.esjp.accounting.transaction.FieldUpdate_Base.java

/**
 * Method is executed on update trigger for the rate field in the debit
 * and credit table inside the transaction form.
 *
 * @param _parameter Parameter as passed from the eFaps API
 * @return list for update trigger/*from www.  java2 s.  co m*/
 * @throws EFapsException on error
 */
public Return update4Rate(final Parameter _parameter) throws EFapsException {
    final Return retVal = new Return();

    try {
        final String postfix = getProperty(_parameter, "TypePostfix");

        final String[] amounts = _parameter.getParameterValues("amount_" + postfix);
        final String[] rates = _parameter.getParameterValues("rate_" + postfix);
        final String[] ratesInv = _parameter.getParameterValues("rate_" + postfix + RateUI.INVERTEDSUFFIX);

        final int pos = getSelectedRow(_parameter);
        final DecimalFormat rateFormater = NumberFormatter.get().getFormatter(0, 8);
        final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter();
        final BigDecimal amount = amounts[pos].isEmpty() ? BigDecimal.ZERO
                : (BigDecimal) rateFormater.parse(amounts[pos]);
        BigDecimal rate = rates[pos].isEmpty() ? BigDecimal.ONE : (BigDecimal) rateFormater.parse(rates[pos]);
        final boolean rateInv = "true".equalsIgnoreCase(ratesInv[pos]);
        if (rateInv && rate.compareTo(BigDecimal.ZERO) != 0) {
            rate = BigDecimal.ONE.divide(rate, 12, BigDecimal.ROUND_HALF_UP);
        }
        final List<Map<String, String>> list = new ArrayList<>();
        final Instance periodInstance = new Period().evaluateCurrentPeriod(_parameter);

        final BigDecimal sum = getSum4UI(_parameter, postfix, null, null);
        final String postfix2 = "Debit".equals(postfix) ? "Credit" : "Debit";
        final BigDecimal sum2 = getSum4UI(_parameter, postfix2, null, null);
        final String sumStr = formater.format(sum) + " " + new Period().getCurrency(periodInstance).getSymbol();
        final String sumStr2 = formater.format(sum.subtract(sum2).abs()) + " "
                + new Period().getCurrency(periodInstance).getSymbol();

        final Map<String, String> map = new HashMap<>();
        map.put("sum" + postfix, sumStr);
        map.put("amountRate_" + postfix,
                formater.format(amount.setScale(8).divide(rate, BigDecimal.ROUND_HALF_UP)));
        map.put("sumTotal", sumStr2);
        list.add(map);

        retVal.put(ReturnValues.VALUES, list);
    } catch (final ParseException e) {
        throw new EFapsException(Transaction_Base.class, "update4Rate.ParseException", e);
    }
    return retVal;
}

From source file:com.healthmarketscience.jackcess.impl.ColumnImpl.java

/**
 * Writes a numeric value.//from   w ww.  j  a va2s  . c  om
 */
private void writeNumericValue(ByteBuffer buffer, Object value) throws IOException {
    Object inValue = value;
    try {
        BigDecimal decVal = toBigDecimal(value);
        inValue = decVal;

        int signum = decVal.signum();
        if (signum < 0) {
            decVal = decVal.negate();
        }

        // write sign byte
        buffer.put((signum < 0) ? NUMERIC_NEGATIVE_BYTE : 0);

        // adjust scale according to this column type (will cause the an
        // ArithmeticException if number has too many decimal places)
        decVal = decVal.setScale(getScale());

        // check precision
        if (decVal.precision() > getPrecision()) {
            throw new IOException(
                    "Numeric value is too big for specified precision " + getPrecision() + ": " + decVal);
        }

        // convert to unscaled BigInteger, big-endian bytes
        byte[] intValBytes = toUnscaledByteArray(decVal, getType().getFixedSize() - 1);
        if (buffer.order() != ByteOrder.BIG_ENDIAN) {
            fixNumericByteOrder(intValBytes);
        }
        buffer.put(intValBytes);
    } catch (ArithmeticException e) {
        throw (IOException) new IOException("Numeric value '" + inValue + "' out of range").initCause(e);
    }
}

From source file:org.kuali.coeus.propdev.impl.print.NIHResearchAndRelatedXmlStream.java

private BigDecimal calculateFundingMonths(DevelopmentProposal developmentProposal,
        BudgetPersonnelDetails budgetPersonnelDetails, String budgetPeriodType) {
    BigDecimal fundingMonths = ScaleTwoDecimal.ZERO.bigDecimalValue();
    if (personExistsInProposal(developmentProposal, budgetPersonnelDetails)
            && budgetPeriodType.equals(budgetPersonnelDetails.getPeriodTypeCode())) {
        if (budgetPersonnelDetails != null) {
            BigDecimal totalMonths = getMonthsBetweenDates(budgetPersonnelDetails.getStartDate(),
                    budgetPersonnelDetails.getEndDate());
            fundingMonths = budgetPersonnelDetails.getPercentEffort().bigDecimalValue()
                    .multiply(new ScaleTwoDecimal(totalMonths).bigDecimalValue());
            fundingMonths = fundingMonths.divide(new ScaleTwoDecimal(100).bigDecimalValue(),
                    RoundingMode.HALF_UP);
        }//w w  w  . jav a  2s .  co  m
    }
    return fundingMonths.setScale(0);
}

From source file:net.starschema.clouddb.jdbc.BQForwardOnlyResultSet.java

/** {@inheritDoc} */
@Override//from   www.j a v  a2  s . c o  m
public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException {
    BigDecimal value = this.getBigDecimal(columnIndex);
    if (value == null) {
        return null;
    }
    return value.setScale(scale);
}

From source file:com.healthmarketscience.jackcess.Column.java

/**
 * Writes a numeric value.// w  ww. j a v a2 s . co m
 */
private void writeNumericValue(ByteBuffer buffer, Object value) throws IOException {
    Object inValue = value;
    try {
        BigDecimal decVal = toBigDecimal(value);
        inValue = decVal;

        boolean negative = (decVal.compareTo(BigDecimal.ZERO) < 0);
        if (negative) {
            decVal = decVal.negate();
        }

        // write sign byte
        buffer.put(negative ? (byte) 0x80 : (byte) 0);

        // adjust scale according to this column type (will cause the an
        // ArithmeticException if number has too many decimal places)
        decVal = decVal.setScale(getScale());

        // check precision
        if (decVal.precision() > getPrecision()) {
            throw new IOException(
                    "Numeric value is too big for specified precision " + getPrecision() + ": " + decVal);
        }

        // convert to unscaled BigInteger, big-endian bytes
        byte[] intValBytes = decVal.unscaledValue().toByteArray();
        int maxByteLen = getType().getFixedSize() - 1;
        if (intValBytes.length > maxByteLen) {
            throw new IOException("Too many bytes for valid BigInteger?");
        }
        if (intValBytes.length < maxByteLen) {
            byte[] tmpBytes = new byte[maxByteLen];
            System.arraycopy(intValBytes, 0, tmpBytes, (maxByteLen - intValBytes.length), intValBytes.length);
            intValBytes = tmpBytes;
        }
        if (buffer.order() != ByteOrder.BIG_ENDIAN) {
            fixNumericByteOrder(intValBytes);
        }
        buffer.put(intValBytes);
    } catch (ArithmeticException e) {
        throw (IOException) new IOException("Numeric value '" + inValue + "' out of range").initCause(e);
    }
}