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

@Deprecated(since = "9")
public BigDecimal setScale(int newScale, int roundingMode) 

Source Link

Document

Returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal 's unscaled value by the appropriate power of ten to maintain its overall value.

Usage

From source file:org.apache.ofbiz.accounting.thirdparty.paypal.PayPalServices.java

public static Map<String, Object> doAuthorization(DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    String orderId = (String) context.get("orderId");
    BigDecimal processAmount = (BigDecimal) context.get("processAmount");
    GenericValue payPalPaymentMethod = (GenericValue) context.get("payPalPaymentMethod");
    OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
    GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context,
            PaymentGatewayServices.AUTH_SERVICE_TYPE);
    Locale locale = (Locale) context.get("locale");

    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "DoAuthorization");
    encoder.add("TRANSACTIONID", payPalPaymentMethod.getString("transactionId"));
    encoder.add("AMT", processAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
    encoder.add("TRANSACTIONENTITY", "Order");
    String currency = (String) context.get("currency");
    if (currency == null) {
        currency = orh.getCurrency();/*from   w  w  w . j a  va2 s .  c  o  m*/
    }
    encoder.add("CURRENCYCODE", currency);

    NVPDecoder decoder = null;
    try {
        decoder = sendNVPRequest(payPalConfig, 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, Object> result = ServiceUtil.returnSuccess();
    Map<String, String> errors = getErrorMessageMap(decoder);
    if (UtilValidate.isNotEmpty(errors)) {
        result.put("authResult", false);
        result.put("authRefNum", "N/A");
        result.put("processAmount", BigDecimal.ZERO);
        if (errors.size() == 1) {
            Map.Entry<String, String> error = errors.entrySet().iterator().next();
            result.put("authCode", error.getKey());
            result.put("authMessage", error.getValue());
        } else {
            result.put("authMessage",
                    "Multiple errors occurred, please refer to the gateway response messages");
            result.put("internalRespMsgs", errors);
        }
    } else {
        result.put("authResult", true);
        result.put("processAmount", new BigDecimal(decoder.get("AMT")));
        result.put("authRefNum", decoder.get("TRANSACTIONID"));
    }
    //TODO: Look into possible PAYMENTSTATUS and PENDINGREASON return codes, it is unclear what should be checked for this type of transaction
    return result;
}

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

@Override
public KualiDecimal calculateExtendedPrice() {
    KualiDecimal extendedPrice = KualiDecimal.ZERO;
    if (ObjectUtils.isNotNull(itemUnitPrice)) {
        if (this.itemType.isAmountBasedGeneralLedgerIndicator()) {
            // SERVICE ITEM: return unit price as extended price
            extendedPrice = new KualiDecimal(this.itemUnitPrice.toString());
        } else if (ObjectUtils.isNotNull(this.getItemQuantity())) {
            BigDecimal calcExtendedPrice = this.itemUnitPrice.multiply(this.itemQuantity.bigDecimalValue());
            // ITEM TYPE (qty driven): return (unitPrice x qty)
            extendedPrice = new KualiDecimal(
                    calcExtendedPrice.setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR));
        }//from   w  w  w. j  a v  a 2s  .com
    }
    return extendedPrice;
}

From source file:org.apache.ofbiz.accounting.thirdparty.paypal.PayPalServices.java

public static Map<String, Object> doCapture(DispatchContext dctx, Map<String, Object> context) {
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    BigDecimal captureAmount = (BigDecimal) context.get("captureAmount");
    GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context,
            PaymentGatewayServices.AUTH_SERVICE_TYPE);
    GenericValue authTrans = (GenericValue) context.get("authTrans");
    Locale locale = (Locale) context.get("locale");
    if (authTrans == null) {
        authTrans = PaymentGatewayServices.getAuthTransaction(paymentPref);
    }/*  w  w  w .  j a  v  a2  s  .  c  om*/

    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "DoCapture");
    encoder.add("AUTHORIZATIONID", authTrans.getString("referenceNum"));
    encoder.add("AMT", captureAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
    encoder.add("CURRENCYCODE", authTrans.getString("currencyUomId"));
    encoder.add("COMPLETETYPE", "NotComplete");

    NVPDecoder decoder = null;
    try {
        decoder = sendNVPRequest(payPalConfig, 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, Object> result = ServiceUtil.returnSuccess();
    Map<String, String> errors = getErrorMessageMap(decoder);
    if (UtilValidate.isNotEmpty(errors)) {
        result.put("captureResult", false);
        result.put("captureRefNum", "N/A");
        result.put("captureAmount", BigDecimal.ZERO);
        if (errors.size() == 1) {
            Map.Entry<String, String> error = errors.entrySet().iterator().next();
            result.put("captureCode", error.getKey());
            result.put("captureMessage", error.getValue());
        } else {
            result.put("captureMessage",
                    "Multiple errors occurred, please refer to the gateway response messages");
            result.put("internalRespMsgs", errors);
        }
    } else {
        result.put("captureResult", true);
        result.put("captureAmount", new BigDecimal(decoder.get("AMT")));
        result.put("captureRefNum", decoder.get("TRANSACTIONID"));
    }
    //TODO: Look into possible PAYMENTSTATUS and PENDINGREASON return codes, it is unclear what should be checked for this type of transaction
    return result;
}

From source file:org.runnerup.export.RunKeeperSynchronizer.java

private String parseForNext(JSONObject resp, List<SyncActivityItem> items) throws JSONException {
    if (resp.has("items")) {
        JSONArray activities = resp.getJSONArray("items");
        for (int i = 0; i < activities.length(); i++) {
            JSONObject item = activities.getJSONObject(i);
            SyncActivityItem ai = new SyncActivityItem();

            String startTime = item.getString("start_time");
            SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss", Locale.US);
            try {
                ai.setStartTime(TimeUnit.MILLISECONDS.toSeconds(format.parse(startTime).getTime()));
            } catch (ParseException e) {
                Log.e(Constants.LOG, e.getMessage());
                return null;
            }/* w ww  .  j  av  a  2s . c o m*/
            Float time = Float.parseFloat(item.getString("duration"));
            ai.setDuration(time.longValue());
            BigDecimal dist = new BigDecimal(Float.parseFloat(item.getString("total_distance")));
            dist = dist.setScale(2, BigDecimal.ROUND_UP);
            ai.setDistance(dist.floatValue());
            ai.setURI(REST_URL + item.getString("uri"));
            ai.setId((long) items.size());
            String sport = item.getString("type");
            if (runkeeper2sportMap.containsKey(sport)) {
                ai.setSport(runkeeper2sportMap.get(sport).getDbValue());
            } else {
                ai.setSport(Sport.OTHER.getDbValue());
            }
            items.add(ai);
        }
    }
    if (resp.has("next")) {
        return REST_URL + resp.getString("next");
    }
    return null;
}

From source file:jp.furplag.util.commons.NumberUtils.java

public static BigDecimal cos(final BigDecimal angle, MathContext mc, boolean isRadians) {
    if (angle == null)
        return null;
    BigDecimal cos = BigDecimal.ONE;
    BigDecimal radians = isRadians ? angle : valueOf(toRadians(angle), BigDecimal.class);
    BigDecimal nSquare = radians.pow(2);
    int index = 0;
    for (BigDecimal factor : COSINE_FACTOR_DECIMAL128) {
        BigDecimal temporary = factor.multiply(nSquare);
        if (index % 2 == 0)
            temporary = temporary.negate();
        cos = cos.add(temporary);//from  www .  j a v  a  2 s.  c o m
        nSquare = nSquare.multiply(radians.pow(2)).setScale(
                ((mc == null ? MathContext.DECIMAL128 : mc).getPrecision() + 2), RoundingMode.HALF_UP);
        index++;
    }

    return cos.setScale((mc == null ? MathContext.DECIMAL128 : mc).getPrecision(), RoundingMode.HALF_UP);
}

From source file:com.osafe.services.OsafePayPalServices.java

public static Map<String, Object> doAuthorization(DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    String orderId = (String) context.get("orderId");
    BigDecimal processAmount = (BigDecimal) context.get("processAmount");
    GenericValue payPalPaymentMethod = (GenericValue) context.get("payPalPaymentMethod");
    OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
    GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context,
            PaymentGatewayServices.AUTH_SERVICE_TYPE);
    Locale locale = (Locale) context.get("locale");

    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "DoAuthorization");
    encoder.add("TRANSACTIONID", payPalPaymentMethod.getString("transactionId"));
    encoder.add("AMT", processAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
    encoder.add("TRANSACTIONENTITY", "Order");
    String currency = (String) context.get("currency");
    if (currency == null) {
        currency = orh.getCurrency();/* www  . ja  v  a  2  s.  co m*/
    }
    encoder.add("CURRENCYCODE", currency);

    NVPDecoder decoder = null;
    try {
        decoder = sendNVPRequest(payPalConfig, 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 unknown error occurred while contacting PayPal");
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    Map<String, String> errors = getErrorMessageMap(decoder);
    if (UtilValidate.isNotEmpty(errors)) {
        result.put("authResult", false);
        result.put("authRefNum", "N/A");
        result.put("processAmount", BigDecimal.ZERO);
        if (errors.size() == 1) {
            Map.Entry<String, String> error = errors.entrySet().iterator().next();
            result.put("authCode", error.getKey());
            result.put("authMessage", error.getValue());
        } else {
            result.put("authMessage",
                    "Multiple errors occurred, please refer to the gateway response messages");
            result.put("internalRespMsgs", errors);
        }
    } else {
        result.put("authResult", true);
        result.put("processAmount", new BigDecimal(decoder.get("AMT")));
        result.put("authRefNum", decoder.get("TRANSACTIONID"));
    }
    //TODO: Look into possible PAYMENTSTATUS and PENDINGREASON return codes, it is unclear what should be checked for this type of transaction
    return result;
}

From source file:com.osafe.services.OsafePayPalServices.java

public static Map<String, Object> doCapture(DispatchContext dctx, Map<String, Object> context) {
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    BigDecimal captureAmount = (BigDecimal) context.get("captureAmount");
    GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context,
            PaymentGatewayServices.AUTH_SERVICE_TYPE);
    GenericValue authTrans = (GenericValue) context.get("authTrans");
    Locale locale = (Locale) context.get("locale");
    if (authTrans == null) {
        authTrans = PaymentGatewayServices.getAuthTransaction(paymentPref);
    }// ww  w  .j  av a  2  s  .c om

    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "DoCapture");
    encoder.add("AUTHORIZATIONID", authTrans.getString("referenceNum"));
    encoder.add("AMT", captureAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
    encoder.add("CURRENCYCODE", authTrans.getString("currencyUomId"));
    encoder.add("COMPLETETYPE", "NotComplete");

    NVPDecoder decoder = null;
    try {
        decoder = sendNVPRequest(payPalConfig, 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 unknown error occurred while contacting PayPal"); //When we will move all the hard coded error message will remove and uncomment code.
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    Map<String, String> errors = getErrorMessageMap(decoder);
    if (UtilValidate.isNotEmpty(errors)) {
        result.put("captureResult", false);
        result.put("captureRefNum", "N/A");
        result.put("captureAmount", BigDecimal.ZERO);
        if (errors.size() == 1) {
            Map.Entry<String, String> error = errors.entrySet().iterator().next();
            result.put("captureCode", error.getKey());
            result.put("captureMessage", error.getValue());
        } else {
            result.put("captureMessage",
                    "Multiple errors occurred, please refer to the gateway response messages");
            result.put("internalRespMsgs", errors);
        }
    } else {
        result.put("captureResult", true);
        result.put("captureAmount", new BigDecimal(decoder.get("AMT")));
        result.put("captureRefNum", decoder.get("TRANSACTIONID"));
    }
    //TODO: Look into possible PAYMENTSTATUS and PENDINGREASON return codes, it is unclear what should be checked for this type of transaction
    return result;
}

From source file:org.kuali.kfs.module.endow.businessobject.Security.java

/**
 * This method sets the unitValue./*  w  ww  .  j  av  a 2  s .c  om*/
 * 
 * @param unitValue
 */
public void setUnitValue(BigDecimal unitValue) {

    if (unitValue != null) {
        this.unitValue = unitValue.setScale(EndowConstants.Scale.SECURITY_UNIT_VALUE, BigDecimal.ROUND_HALF_UP);
    } else {
        this.unitValue = unitValue;
    }
}

From source file:com.salesmanager.core.service.tax.TaxService.java

/**
 * Calculates tax on a BigDecimal price, returns the price with tax
 * //from  www  .  ja  v  a2s .  c om
 * @param amount
 * @param customer
 * @param merchantId
 * @return
 * @throws Exception
 */
@Transactional
public BigDecimal calculateTax(BigDecimal amount, long taxClassId, Customer customer, int merchantId)
        throws Exception {

    // no tax calculation id taxClassId==-1
    if (taxClassId == -1) {
        return amount;
    }

    MerchantService mservice = (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);
    ConfigurationRequest request = new ConfigurationRequest(merchantId, ShippingConstants.MODULE_TAX_BASIS);
    ConfigurationResponse response = mservice.getConfiguration(request);

    String taxBasis = TaxConstants.SHIPPING_TAX_BASIS;

    // get tax basis
    MerchantConfiguration taxConf = response.getMerchantConfiguration(TaxConstants.MODULE_TAX_BASIS);
    if (taxConf != null && !StringUtils.isBlank(taxConf.getConfigurationValue())) {// tax
        // basis
        taxBasis = taxConf.getConfigurationValue();
    }

    Collection taxCollection = null;
    if (taxBasis.equals(TaxConstants.SHIPPING_TAX_BASIS)) {
        taxCollection = taxRateDao.findByCountryIdZoneIdAndClassId(customer.getCustomerCountryId(),
                customer.getCustomerZoneId(), taxClassId, merchantId);
    } else {
        taxCollection = taxRateDao.findByCountryIdZoneIdAndClassId(customer.getCustomerBillingCountryId(),
                customer.getCustomerBillingZoneId(), taxClassId, merchantId);
    }

    BigDecimal currentAmount = new BigDecimal(0);
    currentAmount.setScale(2, BigDecimal.ROUND_HALF_UP);
    if (taxCollection != null) {

        Iterator i = taxCollection.iterator();
        while (i.hasNext()) {

            TaxRate trv = (TaxRate) i.next();
            BigDecimal amountForCalculation = amount;
            if (trv.isPiggyback()) {
                amountForCalculation = amountForCalculation.add(currentAmount);
            }

            double value = ((trv.getTaxRate().doubleValue() * amountForCalculation.doubleValue()) / 100)
                    + amountForCalculation.doubleValue();
            currentAmount = currentAmount.add(new BigDecimal(value));

        }

    }

    return currentAmount;

}

From source file:org.kuali.kfs.module.endow.businessobject.Security.java

/**
 * This method sete the marketValue for the security.
 * /*from   w w  w  . j  ava  2  s  . com*/
 * @param marketValue
 */
public void setMarketValue(BigDecimal marketValue) {

    if (marketValue != null) {
        this.marketValue = marketValue.setScale(EndowConstants.Scale.SECURITY_MARKET_VALUE,
                BigDecimal.ROUND_HALF_UP);
    } else {
        this.marketValue = marketValue;
    }
}