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:org.apache.ofbiz.accounting.thirdparty.verisign.PayflowPro.java

public static Map<String, Object> doExpressCheckout(DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    OrderReadHelper orh = new OrderReadHelper(delegator, paymentPref.getString("orderId"));
    GenericValue payPalPaymentSetting = ProductStoreWorker.getProductStorePaymentSetting(delegator,
            orh.getProductStoreId(), "EXT_PAYPAL", null, true);
    String paymentGatewayConfigId = payPalPaymentSetting.getString("paymentGatewayConfigId");
    String configString = "payment.properties";
    GenericValue payPalPaymentMethod = null;
    try {//from w w  w  .j  a  v  a 2s .c om
        payPalPaymentMethod = paymentPref.getRelatedOne("PaymentMethod", false);
        payPalPaymentMethod = payPalPaymentMethod.getRelatedOne("PayPalPaymentMethod", false);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    BigDecimal processAmount = paymentPref.getBigDecimal("maxAmount");

    Map<String, String> data = new HashMap<String, String>();
    data.put("TRXTYPE", "O");
    data.put("TENDER", "P");
    data.put("PAYERID", payPalPaymentMethod.getString("payerId"));
    data.put("TOKEN", payPalPaymentMethod.getString("expressCheckoutToken"));
    data.put("ACTION", "D");
    // set the amount
    data.put("AMT", processAmount.setScale(2).toPlainString());

    PayflowAPI pfp = init(delegator, paymentGatewayConfigId, null, context);

    // get the base params
    StringBuilder params = makeBaseParams(delegator, paymentGatewayConfigId, null);

    // parse the context parameters
    params.append("&").append(parseContext(data));

    // transmit the request
    if (Debug.verboseOn())
        Debug.logVerbose("Sending to Verisign: " + params.toString(), module);
    String resp;
    if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString,
            "payment.verisign.enable_transmit", "false")) {
        resp = pfp.submitTransaction(params.toString(), pfp.generateRequestId());
    } else {
        resp = "RESULT=0&PAYERID=" + (new Date()).getTime() + "&RESPMSG=Testing";
    }

    Map<String, String> responseMap = parseResponse(resp);

    Map<String, Object> inMap = new HashMap<String, Object>();
    inMap.put("userLogin", userLogin);
    inMap.put("paymentMethodId", payPalPaymentMethod.get("paymentMethodId"));
    inMap.put("transactionId", responseMap.get("PNREF"));
    Map<String, Object> outMap = null;
    try {
        outMap = dispatcher.runSync("updatePayPalPaymentMethod", inMap);
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (ServiceUtil.isError(outMap)) {
        Debug.logError(ServiceUtil.getErrorMessage(outMap), module);
        return outMap;
    }
    return ServiceUtil.returnSuccess();
}

From source file:org.devgateway.ocds.web.rest.controller.CostEffectivenessVisualsController.java

@ApiOperation(value = "Aggregated version of /api/costEffectivenessTenderAmount and "
        + "/api/costEffectivenessAwardAmount."
        + "This endpoint aggregates the responses from the specified endpoints, per year. "
        + "Responds to the same filters.")
@RequestMapping(value = "/api/costEffectivenessTenderAwardAmount", method = { RequestMethod.POST,
        RequestMethod.GET }, produces = "application/json")
public List<DBObject> costEffectivenessTenderAwardAmount(
        @ModelAttribute @Valid final GroupingFilterPagingRequest filter) {

    Future<List<DBObject>> costEffectivenessAwardAmountFuture = controllerLookupService.asyncInvoke(
            new AsyncBeanParamControllerMethodCallable<List<DBObject>, GroupingFilterPagingRequest>() {
                @Override/*www  . j ava 2  s .c  o m*/
                public List<DBObject> invokeControllerMethod(GroupingFilterPagingRequest filter) {
                    return costEffectivenessAwardAmount(filter);
                }
            }, filter);

    Future<List<DBObject>> costEffectivenessTenderAmountFuture = controllerLookupService.asyncInvoke(
            new AsyncBeanParamControllerMethodCallable<List<DBObject>, GroupingFilterPagingRequest>() {
                @Override
                public List<DBObject> invokeControllerMethod(GroupingFilterPagingRequest filter) {
                    return costEffectivenessTenderAmount(filter);
                }
            }, filter);

    //this is completely unnecessary since the #get methods are blocking
    //controllerLookupService.waitTillDone(costEffectivenessAwardAmountFuture, costEffectivenessTenderAmountFuture);

    LinkedHashMap<Object, DBObject> response = new LinkedHashMap<>();

    try {

        costEffectivenessAwardAmountFuture.get()
                .forEach(dbobj -> response.put(getYearMonthlyKey(filter, dbobj), dbobj));
        costEffectivenessTenderAmountFuture.get().forEach(dbobj -> {
            if (response.containsKey(getYearMonthlyKey(filter, dbobj))) {
                Map<?, ?> map = dbobj.toMap();
                map.remove(Keys.YEAR);
                if (filter.getMonthly()) {
                    map.remove(Keys.MONTH);
                }
                response.get(getYearMonthlyKey(filter, dbobj)).putAll(map);
            } else {
                response.put(getYearMonthlyKey(filter, dbobj), dbobj);
            }
        });

    } catch (InterruptedException | ExecutionException e) {
        throw new RuntimeException(e);
    }

    Collection<DBObject> respCollection = response.values();

    respCollection.forEach(dbobj -> {

        BigDecimal totalTenderAmount = BigDecimal.valueOf(dbobj.get(Keys.TOTAL_TENDER_AMOUNT) == null ? 0d
                : ((Number) dbobj.get(Keys.TOTAL_TENDER_AMOUNT)).doubleValue());

        BigDecimal totalAwardAmount = BigDecimal.valueOf(dbobj.get(Keys.TOTAL_AWARD_AMOUNT) == null ? 0d
                : ((Number) dbobj.get(Keys.TOTAL_AWARD_AMOUNT)).doubleValue());

        dbobj.put(Keys.DIFF_TENDER_AWARD_AMOUNT, totalTenderAmount.subtract(totalAwardAmount));

        dbobj.put(Keys.PERCENTAGE_AWARD_AMOUNT,
                totalTenderAmount.compareTo(BigDecimal.ZERO) != 0
                        ? (totalAwardAmount.setScale(15).divide(totalTenderAmount, BigDecimal.ROUND_HALF_UP)
                                .multiply(ONE_HUNDRED))
                        : BigDecimal.ZERO);

        dbobj.put(Keys.PERCENTAGE_DIFF_AMOUNT,
                totalTenderAmount.compareTo(BigDecimal.ZERO) != 0
                        ? (((BigDecimal) dbobj.get(Keys.DIFF_TENDER_AWARD_AMOUNT)).setScale(15)
                                .divide(totalTenderAmount, BigDecimal.ROUND_HALF_UP).multiply(ONE_HUNDRED))
                        : BigDecimal.ZERO);

    });

    return new ArrayList<>(respCollection);
}

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

/**
 * Constructor. Note that trailing zeros are stripped from strikePrice.
 * //from ww  w .j  a  va2s.  c om
 * @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.egov.egf.web.actions.contra.ContraBTCAction.java

private void populateData() {
    voucherHeader = (CVoucherHeader) persistenceService.find("from CVoucherHeader where id=?",
            voucherHeader.getId());/*from  ww w  .  jav a  2s .  c om*/
    final ContraJournalVoucher contraVoucher = (ContraJournalVoucher) persistenceService
            .find("from ContraJournalVoucher where voucherHeaderId.id=?", voucherHeader.getId());
    contraBean.setAccountNumberId(contraVoucher.getFromBankAccountId().getId().toString());
    final String fromBankAndBranchId = contraVoucher.getFromBankAccountId().getBankbranch().getBank().getId()
            .toString() + "-" + contraVoucher.getFromBankAccountId().getBankbranch().getId().toString();
    contraBean.setBankBranchId(fromBankAndBranchId);
    loadBankAccountNumber(contraBean);
    final InstrumentHeader instrumentHeader = contraVoucher.getInstrumentHeaderId();
    contraBean.setChequeNumber(instrumentHeader.getInstrumentNumber());
    final String chequeDate = Constants.DDMMYYYYFORMAT2.format(instrumentHeader.getInstrumentDate());
    contraBean.setChequeDate(chequeDate);
    final BigDecimal instrumentAmount = instrumentHeader.getInstrumentAmount();
    contraBean.setAmount(instrumentAmount == null ? BigDecimal.ZERO.setScale(2) : instrumentAmount.setScale(2));
}

From source file:com.aoindustries.creditcards.TransactionRequest.java

/**
 * Sets the tax amount of the transaction.
 *
 * The amount is normalized to the proper number of decimal places for the selected currency.
 *
 * @throws  IllegalArgumentException  if taxAmount < 0 or is incorrectly formatted for the currency.
 *//*from   w w w .j a  v a2s . com*/
public void setTaxAmount(BigDecimal taxAmount) {
    if (taxAmount == null) {
        this.taxAmount = null;
    } else {
        if (taxAmount.compareTo(BigDecimal.ZERO) < 0)
            throw new LocalizedIllegalArgumentException(accessor,
                    "TransactionRequest.setTaxAmount.taxAmount.lessThanZero");
        try {
            this.taxAmount = taxAmount.setScale(currency.getDefaultFractionDigits());
        } catch (ArithmeticException err) {
            throw new LocalizedIllegalArgumentException(err, accessor,
                    "TransactionRequest.setTaxAmount.taxAmount.cannotNormalize");
        }
    }
}

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

/**
 * Gets the JS 4 exchange rate.//from  w  w  w .  j  a  v  a 2  s  . c  o m
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @param _parameterClone the parameter clone
 * @param _postfix the postfix
 * @return the JS 4 exchange rate
 * @throws EFapsException on error
 */
protected StringBuilder getJS4ExchangeRate(final Parameter _parameter, final Parameter _parameterClone,
        final String _postfix) throws EFapsException {
    final StringBuilder ret = new StringBuilder();
    try {
        final String[] amounts = _parameter.getParameterValues("amount_" + _postfix);
        final String[] currencies = _parameter.getParameterValues("rateCurrencyLink_" + _postfix);
        final String[] selected = _parameter.getParameterValues("posSelect_" + _postfix);

        final ExchangeConfig exConf = getExchangeConfig(_parameter, null);

        for (int i = 0; i < selected.length; i++) {
            if (BooleanUtils.toBoolean(selected[i])) {
                final DateTime date;
                switch (exConf) {
                case DOCDATEPURCHASE:
                case DOCDATESALE:
                    final Instance docInst = Instance
                            .get(_parameter.getParameterValues("docLink_" + _postfix)[i]);
                    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(), currencies[i]));
                final DecimalFormat rateFormater = sale ? rate.getFormatter().getFrmt4SaleRateUI()
                        : rate.getFormatter().getFrmt4RateUI();
                final BigDecimal amountRate = amounts[i].isEmpty() ? BigDecimal.ZERO
                        : (BigDecimal) rateFormater.parse(amounts[i]);

                final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter();

                final String rateStr = sale ? rate.getSaleRateUIFrmt() : rate.getRateUIFrmt();
                final String rateInStr = "" + rate.isInvert();
                final String amountStr = formater.format(amountRate.setScale(12)
                        .divide(sale ? rate.getSaleRate() : rate.getRate(), BigDecimal.ROUND_HALF_UP));

                ret.append(getSetFieldValue(i, "rate_" + _postfix, rateStr))
                        .append(getSetFieldValue(i, "rate_" + _postfix + RateUI.INVERTEDSUFFIX, rateInStr))
                        .append(getSetFieldValue(i, "amountRate_" + _postfix, amountStr));

                ParameterUtil.setParameterValue(_parameterClone, "rate_" + _postfix, i, rateStr);
                ParameterUtil.setParameterValue(_parameterClone, "rate_" + _postfix + RateUI.INVERTEDSUFFIX, i,
                        rateInStr);
                ParameterUtil.setParameterValue(_parameterClone, "amountRate_" + _postfix, i, amountStr);
            }
        }
    } catch (final ParseException e) {
        throw new EFapsException(Transaction_Base.class, "update4Currency.ParseException", e);
    }
    return ret;
}

From source file:com.aoindustries.creditcards.TransactionRequest.java

/**
 * Sets the duty charges of the transaction.
 *
 * The amount is normalized to the proper number of decimal places for the selected currency.
 *
 * @throws  IllegalArgumentException  if dutyAmount < 0 or is incorrectly formatted for the currency.
 *///from   w ww  .j a v  a 2  s. c o m
public void setDutyAmount(BigDecimal dutyAmount) {
    if (dutyAmount == null) {
        this.dutyAmount = null;
    } else {
        if (dutyAmount.compareTo(BigDecimal.ZERO) < 0)
            throw new LocalizedIllegalArgumentException(accessor,
                    "TransactionRequest.setDutyAmount.dutyAmount.lessThanZero");
        try {
            this.dutyAmount = dutyAmount.setScale(currency.getDefaultFractionDigits());
        } catch (ArithmeticException err) {
            throw new LocalizedIllegalArgumentException(err, accessor,
                    "TransactionRequest.setDutyAmount.dutyAmount.cannotNormalize");
        }
    }
}

From source file:com.aoindustries.creditcards.TransactionRequest.java

/**
 * Sets the amount of the transaction.  This amount should not include any tax, shipping charges, or duty.
 * Thus the total amount of the transaction is the amount + taxAmount + shippingAmount + dutyAmount.
 *
 * The amount is normalized to the proper number of decimal places for the selected currency.
 *
 * @throws  IllegalArgumentException  if amount <= 0 or is incorrectly formatted for the currency.
 *///from   w  w  w  .  j  a va  2 s  . c o m
public void setAmount(BigDecimal amount) throws IllegalArgumentException {
    if (amount == null) {
        this.amount = null;
    } else {
        if (amount.compareTo(BigDecimal.ZERO) <= 0)
            throw new LocalizedIllegalArgumentException(accessor,
                    "TransactionRequest.setAmount.amount.lessThanEqualZero");
        try {
            this.amount = amount.setScale(currency.getDefaultFractionDigits());
        } catch (ArithmeticException err) {
            throw new LocalizedIllegalArgumentException(err, accessor,
                    "TransactionRequest.setAmount.amount.cannotNormalize");
        }
    }
}

From source file:org.kalypso.model.wspm.pdb.internal.wspm.ClassChecker.java

/**
 * Check if two class values are different: if yes, add warning
 *///from   ww  w .j av a 2  s  .  c o m
private void checkValues(final BigDecimal local, final BigDecimal remote, final IClassificationClass localClass,
        final IPdbClass remoteClass, final String valueLabel) {
    if (local == null && remote == null)
        return;

    if (local == null && remote != null) {
        addWarning(local, remote, remoteClass.getLabel(), valueLabel);
        return;
    }

    if (local != null && remote == null) {
        addWarning(local, remote, localClass.getDescription(), valueLabel);
        return;
    }

    /* Bring to same scale to avoid false warnings */
    final int localScale = local.scale();
    final int remoteScale = remote.scale();
    final int maxScale = Math.max(localScale, remoteScale);
    final BigDecimal localScaled = local.setScale(maxScale);
    final BigDecimal remoteScaled = remote.setScale(maxScale);

    if (localScaled.compareTo(remoteScaled) == 0)
        return;

    addWarning(local, remote, remoteClass.getLabel(), valueLabel);
}

From source file:com.aoindustries.creditcards.TransactionRequest.java

/**
 * Sets the shipping amount of the transaction.
 *
 * The amount is normalized to the proper number of decimal places for the selected currency.
 *
 * @throws  IllegalArgumentException  if shippingAmount < 0 or is incorrectly formatted for the currency.
 *//*  w  ww .j  a va 2 s  .c o  m*/
public void setShippingAmount(BigDecimal shippingAmount) {
    if (shippingAmount == null) {
        this.shippingAmount = null;
    } else {
        if (shippingAmount.compareTo(BigDecimal.ZERO) < 0)
            throw new LocalizedIllegalArgumentException(accessor,
                    "TransactionRequest.setShippingAmount.shippingAmount.lessThanZero");
        try {
            this.shippingAmount = shippingAmount.setScale(currency.getDefaultFractionDigits());
        } catch (ArithmeticException err) {
            throw new LocalizedIllegalArgumentException(err, accessor,
                    "TransactionRequest.setShippingAmount.shippingAmount.cannotNormalize");
        }
    }
}