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:com.abiquo.api.services.cloud.VirtualApplianceService.java

private BigDecimal rounded(final int significantDigits, final BigDecimal aNumber) {
    return aNumber.setScale(significantDigits, BigDecimal.ROUND_UP);
}

From source file:com.qcadoo.mes.operationTimeCalculations.OrderRealizationTimeServiceImpl.java

@Override
public int evaluateOperationDurationOutOfCycles(final BigDecimal cycles, final Entity operationComponent,
        final Entity productionLine, final boolean maxForWorkstation, final boolean includeTpz,
        final boolean includeAdditionalTime) {
    boolean isTjDivisable = operationComponent.getBooleanField("isTjDivisible");

    Integer workstationsCount = retrieveWorkstationTypesCount(operationComponent, productionLine);
    BigDecimal cyclesPerOperation = cycles;

    if (maxForWorkstation) {
        cyclesPerOperation = cycles.divide(BigDecimal.valueOf(workstationsCount),
                numberService.getMathContext());

        if (!isTjDivisable) {
            cyclesPerOperation = cyclesPerOperation.setScale(0, RoundingMode.CEILING);
        }/*from ww  w  .ja v a 2s  .  co  m*/
    }

    int tj = getIntegerValue(operationComponent.getField("tj"));
    int operationTime = cyclesPerOperation.multiply(BigDecimal.valueOf(tj), numberService.getMathContext())
            .intValue();

    if (includeTpz) {
        int tpz = getIntegerValue(operationComponent.getField("tpz"));
        operationTime += (maxForWorkstation ? tpz : (tpz * workstationsCount));
    }

    if (includeAdditionalTime) {
        int additionalTime = getIntegerValue(operationComponent.getField("timeNextOperation"));
        operationTime += (maxForWorkstation ? additionalTime : (additionalTime * workstationsCount));
    }

    return operationTime;
}

From source file:com.aliyun.fs.oss.nat.BufferReader.java

private void progressPrint() {
    long hasRead = pos + realContentSize - instreamStart;
    double currentProgress = hasRead >= lengthToFetch ? 1.0d : (double) hasRead / lengthToFetch;
    if (currentProgress - lastProgress >= 0.1 || currentProgress == 1.0d) {
        BigDecimal b = new BigDecimal(currentProgress);
        LOG.info("Current progress of reading '" + key + " [" + instreamStart + ":...]' is "
                + b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        lastProgress = currentProgress;//w  w  w.j  a  v  a 2  s .c  o m
    }
}

From source file:com.artivisi.biller.simulator.gateway.pln.PlnGateway.java

private boolean handleInquiryPostpaid(ISOSource src, ISOMsg msg, ISOMsg response)
        throws ISOException, IOException, VetoException {
    String bit48Request = msg.getString(48);
    if (bit48Request.length() != 19) {
        logger.error("[POSTPAID] - [INQ-REQ] - Invalid bit 48 [{}]", bit48Request);
        response.set(39, ResponseCode.ERROR_INVALID_MESSAGE);
        src.send(response);/*  w  ww  . j a v a 2s .co  m*/
        return true;
    }

    String mitra = bit48Request.substring(0, 7);
    if (billerSimulatorService.findMitraByKode(mitra.trim()) == null) {
        logger.debug("[POSTPAID] - [INQ-REQ] - Mitra [{}]", mitra);
        logger.error("[POSTPAID] - [INQ-REQ] - Kode mitra tidak ditemukan [{}]", mitra);
        response.set(39, ResponseCode.ERROR_UNREGISTERED_SWITCHING);
        src.send(response);
        return true;
    }

    String idpel = bit48Request.substring(7);
    Pelanggan p = plnSimulatorService.findPelangganByIdpel(idpel);
    if (p == null) {
        logger.error("[POSTPAID] - [INQ-REQ] - IDPEL tidak ditemukan [{}]", idpel);
        response.set(39, ResponseCode.ERROR_UNKNOWN_SUBSCRIBER);
        src.send(response);
        return true;
    }

    if (!ResponseCode.SUCCESSFUL.equals(p.getResponseCode())) {
        logger.error("[POSTPAID] - [INQ-REQ] - Pelanggan diset untuk RC [{}]", p.getResponseCode());
        response.set(39, p.getResponseCode());
        src.send(response);
        return true;
    }

    List<TagihanPascabayar> daftarTagihan = plnSimulatorService.findTagihan(p);
    if (daftarTagihan.size() < 1) {
        logger.error("[POSTPAID] - [INQ-REQ] - Tagihan untuk idpel [{}] tidak ada", idpel);
        response.set(39, ResponseCode.ERROR_CURRENT_BILL_IS_NOT_AVAILABLE);
        src.send(response);
        return true;
    }

    List<TagihanPascabayar> tagihanDikirim;
    if (daftarTagihan.size() > 4) {
        tagihanDikirim = daftarTagihan.subList(0, 4);
    } else {
        tagihanDikirim = daftarTagihan;
    }

    BigDecimal amount = BigDecimal.ZERO;
    for (TagihanPascabayar tagihanPascabayar : tagihanDikirim) {
        amount = amount.add(tagihanPascabayar.getBill());
        amount = amount.add(tagihanPascabayar.getDenda());
    }

    response.set(4,
            "360" + "0" + StringUtils.leftPad(amount.setScale(0, RoundingMode.HALF_EVEN).toString(), 12, "0"));

    InquiryPostpaidResponse ipr = new InquiryPostpaidResponse();
    ipr.setBank(msg.getString(32));
    ipr.setSwitcher(mitra);
    ipr.setStan(msg.getString(11));

    for (TagihanPascabayar tagihanPascabayar : tagihanDikirim) {
        InquiryPostpaidResponseDetail detail = new InquiryPostpaidResponseDetail();
        detail.setTagihanPascabayar(tagihanPascabayar);
        detail.setInquiryPostpaidResponse(ipr);
        ipr.getDetails().add(detail);
    }

    plnService.save(ipr);

    StringBuffer bit48Response = createBit48InquiryPostpaidResponse(bit48Request, p, daftarTagihan,
            tagihanDikirim, ipr);

    response.set(39, ResponseCode.SUCCESSFUL);
    response.set(48, bit48Response.toString());

    try {
        logger.info("[POSTPAID] - [INQ-REQ] - Pelanggan diset untuk hold [{}]", p.getHoldResponse());
        Thread.sleep(p.getHoldResponse());
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }

    src.send(response);
    return true;
}

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   ww w.j a  v a 2s  . com*/
        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();// ww  w.j a v  a2  s  .c om
    }
    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);
    }/*from   www.j  a  v a2s  .c  o m*/

    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:com.salesmanager.core.service.tax.TaxService.java

/**
 * Calculates tax on a BigDecimal price, returns the price with tax
 * //from   w w w. ja va2 s  .c o  m
 * @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:act.reports.dao.AllInvoicesDAO.java

public String roundUp(float d, int decimalPlace) {
    BigDecimal bd = new BigDecimal(Float.toString(d));
    bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
    return bd.toString();
}