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.egov.egf.web.actions.report.ExpenseJournalVoucherPrintAction.java

protected Map<String, Object> getParamMap() {
    final Map<String, Object> paramMap = new HashMap<>();
    paramMap.put("voucherNumber", getVoucherNumber());
    paramMap.put("voucherDate", getVoucherDate());
    paramMap.put("voucherDescription", getVoucherDescription());
    if (voucher != null && voucher.getState() != null)
        loadInboxHistoryData(voucher.getStateHistory(), paramMap);
    if (billRegistermis != null) {
        paramMap.put("billDate",
                Constants.DDMMYYYYFORMAT2.format(billRegistermis.getEgBillregister().getBilldate()));
        paramMap.put("partyBillNumber", billRegistermis.getPartyBillNumber());
        paramMap.put("serviceOrder", billRegistermis.getNarration());
        paramMap.put("partyName", billRegistermis.getPayto());
        paramMap.put("billNumber", billRegistermis.getEgBillregister().getBillnumber());
        final BigDecimal billamount = billRegistermis.getEgBillregister().getBillamount();
        final String amountInFigures = billamount == null ? " " : billamount.setScale(2).toPlainString();
        final String amountInWords = billamount == null ? " "
                : NumberToWordConverter.amountInWordsWithCircumfix(billamount);
        paramMap.put("certificate",
                getText("ejv.report.text", new String[] { amountInFigures, amountInWords }));
    }/* ww  w  .  j  av a2  s  .  c  o  m*/
    paramMap.put("ulbName", ReportUtil.getCityName());

    return paramMap;
}

From source file:com.twitter.elephantbird.pig.load.HBaseSlice.java

@Override
public float getProgress() throws IOException {

    // No way to know max.. just return 0. Sorry, reporting on the last slice is janky.
    // So is reporting on the first slice, by the way -- it will start out too high, possibly at 100%.
    if (endRow_.length == 0)
        return 0;
    byte[] lastPadded = m_lastRow_;
    if (m_lastRow_.length < endRow_.length) {
        lastPadded = Bytes.padTail(m_lastRow_, endRow_.length - m_lastRow_.length);
    }//from w ww .j a va  2s .  co  m
    if (m_lastRow_.length < startRow_.length) {
        lastPadded = Bytes.padTail(m_lastRow_, startRow_.length - m_lastRow_.length);
    }
    byte[] prependHeader = { 1, 0 };
    BigInteger bigLastRow = new BigInteger(Bytes.add(prependHeader, lastPadded));
    BigDecimal processed = new BigDecimal(bigLastRow.subtract(bigStart_));
    try {
        BigDecimal progress = processed.setScale(3).divide(bigRange_, BigDecimal.ROUND_HALF_DOWN);
        return progress.floatValue();
    } catch (java.lang.ArithmeticException e) {
        return 0;
    }
}

From source file:org.key2gym.business.services.CashServiceBean.java

/**
 * Validates a money amount./*  w  w  w  .j a  v a2  s . com*/
 * 
 * @param value the amount to validate
 * @throws ValidationException if the amount is invalid
 */
public void validateAmount(BigDecimal value) throws ValidationException {
    if (value == null) {
        throw new NullPointerException("The amount is null."); //NOI18N
    }

    if (value.scale() > 2) {
        throw new ValidationException(getString("Invalid.Money.TwoDigitsAfterDecimalPointMax"));
    }

    value = value.setScale(2);

    if (value.precision() > 6) {
        throw new ValidationException(getString("Invalid.CashAdjustment.LimitReached"));
    }
}

From source file:org.apache.ofbiz.accounting.thirdparty.paypal.PayPalServices.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"));
    Locale locale = (Locale) context.get("locale");

    GenericValue payPalPaymentSetting = getPaymentMethodGatewayPayPal(dctx, context, null);
    GenericValue payPalPaymentMethod = null;
    try {//from   w ww . j  a  v  a2  s  .  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");

    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "DoExpressCheckoutPayment");
    encoder.add("TOKEN", payPalPaymentMethod.getString("expressCheckoutToken"));
    encoder.add("PAYMENTACTION", "Order");
    encoder.add("PAYERID", payPalPaymentMethod.getString("payerId"));
    // set the amount
    encoder.add("AMT", processAmount.setScale(2).toPlainString());
    encoder.add("CURRENCYCODE", orh.getCurrency());
    BigDecimal grandTotal = orh.getOrderGrandTotal();
    BigDecimal shippingTotal = orh.getShippingTotal().setScale(2, BigDecimal.ROUND_HALF_UP);
    BigDecimal taxTotal = orh.getTaxTotal().setScale(2, BigDecimal.ROUND_HALF_UP);
    BigDecimal subTotal = grandTotal.subtract(shippingTotal).subtract(taxTotal).setScale(2,
            BigDecimal.ROUND_HALF_UP);
    encoder.add("ITEMAMT", subTotal.toPlainString());
    encoder.add("SHIPPINGAMT", shippingTotal.toPlainString());
    encoder.add("TAXAMT", taxTotal.toPlainString());

    NVPDecoder decoder = null;
    try {
        decoder = sendNVPRequest(payPalPaymentSetting, encoder);
    } catch (PayPalException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (decoder == null) {
        return ServiceUtil
                .returnError(UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale));
    }

    Map<String, String> errorMessages = getErrorMessageMap(decoder);
    if (UtilValidate.isNotEmpty(errorMessages)) {
        if (errorMessages.containsKey("10417")) {
            // "The transaction cannot complete successfully,  Instruct the customer to use an alternative payment method"
            // I've only encountered this once and there's no indication of the cause so the temporary solution is to try again
            boolean retry = context.get("_RETRY_") == null || (Boolean) context.get("_RETRY_");
            if (retry) {
                context.put("_RETRY_", false);
                return PayPalServices.doExpressCheckout(dctx, context);
            }
        }
        return ServiceUtil.returnError(UtilMisc.toList(errorMessages.values()));
    }

    Map<String, Object> inMap = new HashMap<String, Object>();
    inMap.put("userLogin", userLogin);
    inMap.put("paymentMethodId", payPalPaymentMethod.get("paymentMethodId"));
    inMap.put("transactionId", decoder.get("TRANSACTIONID"));

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

private static void addCartDetails(Map<String, String> parameterMap, ShoppingCart cart)
        throws GenericEntityException {
    parameterMap.put("CURRENCY", cart.getCurrency());
    int line = 0;
    for (ShoppingCartItem item : cart.items()) {
        //paramMap.put("L_NUMBER" + line, item.getProductId());
        parameterMap.put("L_NAME" + line, item.getName());
        parameterMap.put("L_DESC" + line, item.getDescription());
        parameterMap.put("L_AMT" + line, item.getBasePrice().setScale(2).toPlainString());
        parameterMap.put("L_QTY" + line, item.getQuantity().toBigInteger().toString());
        line++;/*from  www . j  a v  a  2 s  . c om*/
        BigDecimal otherAdjustments = item.getOtherAdjustments();
        if (otherAdjustments.compareTo(BigDecimal.ZERO) != 0) {
            parameterMap.put("L_NAME" + line, item.getName() + " Adjustments");
            parameterMap.put("L_DESC" + line, "Adjustments for item: " + item.getName());
            parameterMap.put("L_AMT" + line, otherAdjustments.setScale(2).toPlainString());
            parameterMap.put("L_QTY" + line, "1");
            line++;
        }
    }
    BigDecimal otherAdjustments = cart.getOrderOtherAdjustmentTotal();
    if (otherAdjustments.compareTo(BigDecimal.ZERO) != 0) {
        parameterMap.put("L_NAME" + line, "Order Adjustments");
        parameterMap.put("L_AMT" + line, otherAdjustments.setScale(2).toPlainString());
        parameterMap.put("L_QTY" + line, "1");
        line++;
    }
    parameterMap.put("ITEMAMT", cart.getSubTotal().add(otherAdjustments).setScale(2).toPlainString());
    parameterMap.put("TAXAMT", cart.getTotalSalesTax().setScale(2).toPlainString());
    parameterMap.put("FREIGHTAMT", cart.getTotalShipping().setScale(2).toPlainString());
    parameterMap.put("AMT", cart.getGrandTotal().setScale(2).toPlainString());

    if (!cart.shippingApplies()) {
        parameterMap.put("NOSHIPPING", "1");
    } else {
        GenericValue shippingAddress = cart.getShippingAddress();
        parameterMap.put("ADDROVERRIDE", "1");
        parameterMap.put("SHIPTOSTREET", StringUtils.left(shippingAddress.getString("address1"), 30));
        parameterMap.put("SHIPTOSTREET2", StringUtils.left(shippingAddress.getString("address2"), 30));
        parameterMap.put("SHIPTOCITY", StringUtils.left(shippingAddress.getString("city"), 40));
        if (shippingAddress.getString("stateProvinceGeoId") != null
                && !"_NA_".equals(shippingAddress.getString("stateProvinceGeoId"))) {
            GenericValue stateProvinceGeo = shippingAddress.getRelatedOne("StateProvinceGeo", false);
            parameterMap.put("SHIPTOSTATE", StringUtils.left(stateProvinceGeo.getString("geoCode"), 40));
        }
        parameterMap.put("SHIPTOZIP", StringUtils.left(shippingAddress.getString("postalCode"), 16));
        GenericValue countryGeo = shippingAddress.getRelatedOne("CountryGeo", false);
        parameterMap.put("SHIPTOCOUNTRY", StringUtils.left(countryGeo.getString("geoCode"), 2));
    }
}

From source file:com.osafe.services.OsafePayPalServices.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"));
    Locale locale = (Locale) context.get("locale");

    GenericValue payPalPaymentSetting = getPaymentMethodGatewayPayPal(dctx, context, null);
    GenericValue payPalPaymentMethod = null;
    try {//  ww  w. j av a  2 s  .co m
        payPalPaymentMethod = paymentPref.getRelatedOne("PaymentMethod");
        payPalPaymentMethod = payPalPaymentMethod.getRelatedOne("PayPalPaymentMethod");
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    BigDecimal processAmount = paymentPref.getBigDecimal("maxAmount");

    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "DoExpressCheckoutPayment");
    encoder.add("TOKEN", payPalPaymentMethod.getString("expressCheckoutToken"));
    encoder.add("PAYMENTACTION", "Order");
    encoder.add("PAYERID", payPalPaymentMethod.getString("payerId"));
    // set the amount
    encoder.add("AMT", processAmount.setScale(2).toPlainString());
    encoder.add("CURRENCYCODE", orh.getCurrency());
    BigDecimal grandTotal = orh.getOrderGrandTotal();
    BigDecimal shippingTotal = orh.getShippingTotal().setScale(2, BigDecimal.ROUND_HALF_UP);
    BigDecimal taxTotal = orh.getTaxTotal().setScale(2, BigDecimal.ROUND_HALF_UP);
    BigDecimal subTotal = grandTotal.subtract(shippingTotal).subtract(taxTotal).setScale(2,
            BigDecimal.ROUND_HALF_UP);
    encoder.add("ITEMAMT", subTotal.toPlainString());
    encoder.add("SHIPPINGAMT", shippingTotal.toPlainString());
    encoder.add("TAXAMT", taxTotal.toPlainString());

    NVPDecoder decoder = null;
    try {
        decoder = sendNVPRequest(payPalPaymentSetting, encoder);
    } catch (PayPalException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (decoder == null) {
        /*            return ServiceUtil.returnError(UtilProperties.getMessage(resource, 
            "AccountingPayPalUnknownError", locale));*/
        return ServiceUtil.returnError("An error occurred while communicating with PayPal");
    }

    Map<String, String> errorMessages = getErrorMessageMap(decoder);
    if (UtilValidate.isNotEmpty(errorMessages)) {
        if (errorMessages.containsKey("10417")) {
            // "The transaction cannot complete successfully,  Instruct the customer to use an alternative payment method"
            // I've only encountered this once and there's no indication of the cause so the temporary solution is to try again
            boolean retry = context.get("_RETRY_") == null || (Boolean) context.get("_RETRY_");
            if (retry) {
                context.put("_RETRY_", false);
                return OsafePayPalServices.doExpressCheckout(dctx, context);
            }
        }
        return ServiceUtil.returnError(UtilMisc.toList(errorMessages.values()));
    }

    Map<String, Object> inMap = FastMap.newInstance();
    inMap.put("userLogin", userLogin);
    inMap.put("paymentMethodId", payPalPaymentMethod.get("paymentMethodId"));
    inMap.put("transactionId", decoder.get("TRANSACTIONID"));

    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:fragment.web.AdminControllerTest.java

@Test
public void testEditCreditExposurePost() throws Exception {
    AccountType expected = accountTypeService.locateAccountTypeName("Retail");
    expected.getAccountTypeCreditExposureList().get(0).setCreditExposureLimit(BigDecimal.TEN);
    AccountTypeForm form = new AccountTypeForm(expected);
    BindingResult result = validate(form);
    String view = controller.editcreditexposure(form, result, map);
    Assert.assertEquals("success", view);
    AccountType found = accountTypeService.locateAccountTypeName("Retail");
    BigDecimal bd = BigDecimal.TEN;
    bd = bd.setScale(4);
    Assert.assertEquals(found.getAccountTypeCreditExposureList().get(0).getCreditExposureLimit(), bd);
}

From source file:fragment.web.AdminControllerTest.java

@Test
public void testEditInitialDeposit() throws Exception {

    AccountType accountType = accountTypeDAO.find(3L);
    accountType.getAccountTypeCreditExposureList().get(0).setInitialDeposit(BigDecimal.TEN);
    AccountTypeForm form = new AccountTypeForm(accountType);
    BindingResult result = validate(form);
    String resultString = controller.editInitialDeposit(form, result, map);
    Assert.assertNotNull(resultString);/*  w ww  . j  a va 2s.c  o m*/
    Assert.assertEquals("success", resultString);
    BigDecimal bd = BigDecimal.TEN;
    bd = bd.setScale(4);
    Assert.assertEquals(bd, accountType.getAccountTypeCreditExposureList().get(0).getInitialDeposit());
}

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.j  a v  a  2s. c  o  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;
}

From source file:com.devnexus.ting.web.controller.RegisterController.java

private BigDecimal getTotal(RegistrationDetails registerForm) {
    BigDecimal total = BigDecimal.ZERO;

    for (TicketOrderDetail order : registerForm.getOrderDetails()) {

        total = total.add(getOrderPrice(order));
    }/*from w w  w.ja v a2 s  .  co  m*/

    return total.setScale(2);
}