Example usage for java.math BigDecimal valueOf

List of usage examples for java.math BigDecimal valueOf

Introduction

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

Prototype

public static BigDecimal valueOf(double val) 

Source Link

Document

Translates a double into a BigDecimal , using the double 's canonical string representation provided by the Double#toString(double) method.

Usage

From source file:hr.diskobolos.service.impl.DashboardServiceImpl.java

private double calculatePercentage(Integer totalPoints, Integer categoryPoints) {
    if (categoryPoints == null) {
        return 0.0;
    }//from   w w  w .ja v a 2  s  . c o  m
    return BigDecimal.valueOf((double) (categoryPoints * 100) / (double) totalPoints)
            .setScale(2, RoundingMode.HALF_UP).doubleValue();
}

From source file:de.hybris.platform.configurablebundleservices.bundle.impl.FindBundlePricingWithCurrentPriceFactoryStrategyTest.java

@Test
public void testFindDiscountValuesPlanWinsAgainstRule() throws CalculationException {
    given(bundleRuleService.getChangePriceBundleRuleForOrderEntry(masterEntry)).willReturn(priceRule);
    given(priceRule.getPrice()).willReturn(BigDecimal.valueOf(RULE_HIGH_PRICE.doubleValue()));
    given(priceRule.getId()).willReturn("priceRule");
    given(commercePriceService.getSubscriptionPricePlanForEntry(childEntry)).willReturn(pricePlan);
    given(commercePriceService.getFirstRecurringPriceFromPlan(pricePlan)).willReturn(recurringChargeEntry1);
    final List<DiscountValue> discounts = bundlePriceFactory.findDiscountValues(childEntry);
    assertEquals("", 1, discounts.size());
    final DiscountValue discount = discounts.iterator().next();
    assertEquals("", "recurringChargeEntry1", discount.getCode());
    assertEquals(LAST_RECURRING_PRICE.doubleValue() - FIRST_RECURRING_PRICE.doubleValue(), discount.getValue(),
            0.005);//  w  ww  .j a  v a 2s  . c  o m
}

From source file:org.openvpms.archetype.rules.stock.ChargeStockUpdaterTestCase.java

/**
 * Verifies that stock is updated correctly if an item is saved twice in the one transaction, but the first
 * save is incomplete./*from www  .  jav  a 2s  . com*/
 */
@Test
public void testPartialSaveInTxn() {
    final List<FinancialAct> acts = createInvoice();
    final FinancialAct invoice = acts.get(0);
    final FinancialAct item = acts.get(1);
    BigDecimal initialQuantity = BigDecimal.ZERO;
    BigDecimal quantity = BigDecimal.valueOf(5);

    item.setQuantity(quantity);

    checkEquals(initialQuantity, getStock(stockLocation, product));
    BigDecimal expected = getQuantity(initialQuantity, quantity, false);

    TransactionTemplate template = new TransactionTemplate(txnManager);
    template.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            save(item);
            save(item);
            save(invoice);
        }
    });
    checkEquals(expected, getStock(stockLocation, product));

    save(acts); // stock shouldn't change if resaved
    checkEquals(expected, getStock(stockLocation, product));
}

From source file:org.osgp.adapter.protocol.dlms.domain.commands.DlmsHelperService.java

public DlmsMeterValue getScaledMeterValue(final DataObject value, final DataObject scalerUnitObject,
        final String description) throws ProtocolAdapterException {
    LOGGER.debug(this.getDebugInfo(value));
    LOGGER.debug(this.getDebugInfo(scalerUnitObject));
    final Long rawValue = this.readLong(value, description);
    if (rawValue == null) {
        return null;
    }/* w  w  w.  j av  a  2s .c  om*/

    if (!scalerUnitObject.isComplex()) {
        throw new ProtocolAdapterException("complex data (structure) expected while retrieving scaler and unit."
                + this.getDebugInfo(scalerUnitObject));
    }
    final List<DataObject> dataObjects = scalerUnitObject.value();
    if (dataObjects.size() != 2) {
        throw new ProtocolAdapterException(
                "expected 2 values while retrieving scaler and unit." + this.getDebugInfo(scalerUnitObject));
    }
    final int scaler = this.readLongNotNull(dataObjects.get(0), description).intValue();
    final DlmsUnit unit = DlmsUnit
            .fromDlmsEnum(this.readLongNotNull(dataObjects.get(1), description).intValue());

    // determine value
    BigDecimal scaledValue = BigDecimal.valueOf(rawValue);
    if (scaler != 0) {
        scaledValue = scaledValue.multiply(BigDecimal.valueOf(Math.pow(10, scaler)));
    }

    return new DlmsMeterValue(scaledValue, unit);
}

From source file:com.amazonaws.util.DateUtils.java

/**
 * Formats the give date object into an AWS Service format.
 *//*from w ww  . j a va 2 s. c  o  m*/
public static String formatServiceSpecificDate(Date date) {
    if (date == null)
        return null;
    BigDecimal dateValue = BigDecimal.valueOf(date.getTime());
    return dateValue.scaleByPowerOfTen(0 - AWS_DATE_MILLI_SECOND_PRECISION).toPlainString();
}

From source file:com.epam.cme.facades.bundle.impl.DefaultGuidedSellingFacade.java

protected ProductSearchPageData<SearchStateData, ProductData> enrichSearchResult(
        final ProductSearchPageData<SearchStateData, ProductData> searchPageData, final String componentId,
        final String componentVersion, final Integer bundleNo) {
    final CartModel cartModel = getCartService().getSessionCart();
    final BundleTemplateModel bundleModel = getBundleTemplateService().getBundleTemplateForCode(componentId,
            componentVersion);//from  w w  w. j  av a 2 s .  com

    // bundle prices
    for (final ProductData productData : searchPageData.getResults()) {
        final ProductModel product = getProductService().getProductForCode(productData.getCode());
        final ChangeProductPriceBundleRuleModel priceRule = getBundleRuleService()
                .getChangePriceBundleRule(cartModel, bundleModel, product, bundleNo.intValue());
        SubscriptionPricePlanModel pricePlan = null;

        if (product instanceof SubscriptionProductModel) {
            pricePlan = getCommercePriceService()
                    .getSubscriptionPricePlanForProduct((SubscriptionProductModel) product);
        }

        final Double bestPrice = getMinPriceOfRuleAndPlan(pricePlan, priceRule);

        if (bestPrice != null) {
            final PriceData priceData = getPriceDataFactory().create(PriceDataType.BUY,
                    BigDecimal.valueOf(bestPrice.doubleValue()), cartModel.getCurrency().getIsocode());

            productData.setThisBundleProductPrice(priceData);
        }
    }

    // disable rules
    for (final ProductData productData : searchPageData.getResults()) {
        final ProductModel product = getProductService().getProductForCode(productData.getCode());
        final String disableMessage = getBundleCommerceCartService()
                .checkAndGetReasonForDisabledProductInComponent(cartModel, product, bundleModel,
                        bundleNo.intValue(), true);
        if (disableMessage != null) {
            productData.setDisabled(true);
            productData.setDisabledMessage(disableMessage);
        }
    }

    return searchPageData;
}

From source file:net.pms.util.Rational.java

/**
 * Returns an instance that represents the value of {@code value}.
 *
 * @param value the value.// ww  w . jav  a2s  . c  o  m
 * @return An instance that represents the value of {@code value}.
 */
@Nonnull
public static Rational valueOf(double value) {
    if (value == Double.POSITIVE_INFINITY) {
        return POSITIVE_INFINITY;
    }
    if (value == Double.NEGATIVE_INFINITY) {
        return NEGATIVE_INFINITY;
    }
    if (Double.isNaN(value)) {
        return NaN;
    }
    return valueOf(BigDecimal.valueOf(value));
}

From source file:com.epam.cme.facades.converters.populator.DeviceBundleTabsPopulator.java

/**
 * Hook to call additional populators for different purposes. For Devices we are populating the
 * standard price of the according plan. Afterwards we are finding possible price rules for the
 * device product as well as for the plan product and storing the cheapest ones in the plan DTO
 * as <code>otherBundleProductPrice</code> for the cheapest device price and as
 * <code>thisBundleProductPrice</code> for the cheapest plan price.
 * /*  ww  w. j  a v  a  2  s.  c  o  m*/
 * @param sourceComponent
 *            in this case e.g. the "Smartphone-Handset" component
 * @param targetComponent
 *            in this case e.g. the "Smartphone-Plan" component
 * @param productModel
 *            in this case the Model of the device product
 * @param productData
 *            in this case the DTO of the device product
 * @param subscriptionProductModel
 *            in this case the Model of the plan product
 * @param subscriptionProductData
 *            in this case the DTO of the plan product
 */
@Override
protected void callPopulators(final SOURCETEMPLATE sourceComponent, final SOURCETEMPLATE targetComponent,
        final SOURCEPRODUCT productModel, final TARGETPRODUCT productData,
        final SubscriptionProductModel subscriptionProductModel, final ProductData subscriptionProductData) {
    getProductPricePopulator().populate(subscriptionProductModel, subscriptionProductData);
    getSubscriptionProductPricePopulator().populate(subscriptionProductModel, subscriptionProductData);
    getProductDescriptionPopulator().populate(subscriptionProductModel, subscriptionProductData);
    getProductClassificationPopulator().populate(subscriptionProductModel, subscriptionProductData);

    final CurrencyModel currency = getCommonI18NService().getCurrentCurrency();

    final ChangeProductPriceBundleRuleModel devicePriceRule = getBundleRuleService()
            .getChangePriceBundleRule(sourceComponent, productModel, subscriptionProductModel, currency);
    subscriptionProductData.setOtherBundleProductPrice(devicePriceRule == null ? productData.getPrice()
            : getPriceDataFactory().create(PriceDataType.BUY, devicePriceRule.getPrice(),
                    currency.getIsocode()));

    final ChangeProductPriceBundleRuleModel planPriceRule = getBundleRuleService()
            .getChangePriceBundleRule(targetComponent, subscriptionProductModel, productModel, currency);
    final BigDecimal planPriceRulePrice = planPriceRule == null ? null : planPriceRule.getPrice();

    final SubscriptionPricePlanData pricePlan = (SubscriptionPricePlanData) subscriptionProductData.getPrice();
    BigDecimal pricePlanLowestPrice = BigDecimal.ZERO;
    BigDecimal discountPrice = BigDecimal.ZERO;

    if (pricePlan != null && CollectionUtils.isNotEmpty(pricePlan.getRecurringChargeEntries())) {
        final RecurringChargeEntryData lowestPriceChargeEntry = pricePlan.getRecurringChargeEntries().iterator()
                .next();
        pricePlanLowestPrice = lowestPriceChargeEntry.getPrice().getValue();
    }

    if (planPriceRulePrice == null || pricePlanLowestPrice.doubleValue() < planPriceRulePrice.doubleValue()) {
        discountPrice = pricePlanLowestPrice;
    } else {
        discountPrice = BigDecimal.valueOf(planPriceRulePrice.doubleValue());
    }

    subscriptionProductData.setThisBundleProductPrice(
            getPriceDataFactory().create(PriceDataType.BUY, discountPrice, currency.getIsocode()));
}

From source file:com.algomedica.service.LicenseManagerServiceImpl.java

@Override
public Customer updateLicense(LicenseForm licenseForm, long userId) {
    Customer customer;// w  w  w.j a va  2  s . c om
    try {
        if (licenseForm != null && StringUtils.isNotEmpty(licenseForm.getLsmacAddress())
                && StringUtils.isNotBlank(licenseForm.getLsType()) && licenseForm.getLsExipryDays() != 0) {
            LicenseDetail detail = licenseDao.getLicenseById(licenseForm.getId());
            if (detail == null) {

                throw new ApplicationException(ErrorCodesConstants.INVALID_LICENSE_ID_CODE,
                        ErrorCodesConstants.INVALID_LICENSE_ID);
            }

            if (!detail.getLsMacAddress().equals(licenseForm.getLsmacAddress().replaceAll("..(?!$)", "$0:"))) {

                if (licenseDao.getLicenceByMacAddress(
                        licenseForm.getLsmacAddress().replaceAll("..(?!$)", "$0:")) != null) {
                    LOGGER.error(ErrorCodesConstants.DUPLICATE_MAC_ADDRESS);
                    throw new ApplicationException(ErrorCodesConstants.DUPLICATE_MAC_ADDRESS_CODE,
                            ErrorCodesConstants.DUPLICATE_MAC_ADDRESS);
                }

            }

            customer = detail.getOrganization();
            if (checkForRegeneration(licenseForm, detail)) {
                LicenseDetail licenseDetail = (LicenseDetail) detail.clone();
                licenseDetail.setId(null);

                licenseDetail.setLsLicenseType(licenseForm.getLsType());
                String macAddress = licenseForm.getLsmacAddress().replaceAll("..(?!$)", "$0:");
                licenseDetail.setLsMacAddress(macAddress);

                licenseDetail.setLsCategory(licenseForm.getLsCategory());

                licenseDetail.setLsExipryDate(
                        calculateExpiryDate(detail.getLsExipryDate(), licenseForm.getLsExipryDays()));
                licenseDetail.setLsExpiryDays(BigDecimal.valueOf(licenseForm.getLsExipryDays()));

                // generate license function calling area
                LicenseManager lm = new LicenseManager();
                LicenseContent lc = new LicenseContent(detail.getOrganization().getOrgName(),
                        licenseDetail.getLsMacAddress().replace(":", ""), licenseDetail.getLsLicenseType(),
                        getTime(licenseDetail.getLsExipryDate().getTime()), licenseForm.getLsCategory());
                licenseDetail = lm.generateLicenseKey(lc, licenseDetail);
                licenseDetail.setLsCost(BigDecimal.valueOf(Double.parseDouble(licenseForm.getLsCost())));
                licenseDetail.setLsCost(BigDecimal.valueOf(Double.parseDouble(licenseForm.getLsCost())));
                licenseDetail.setLsCategory(licenseForm.getLsCategory());
                licenseDetail.setLsMacAddress(macAddress);
                licenseDetail.setLsModelName(licenseForm.getLsmodelName());
                licenseDetail.setLsModelNumber(licenseForm.getLsmodelNumber());
                licenseDetail.setLsOpsEmail(licenseForm.getLsOpsEmail());
                licenseDetail.setLsOpsName(licenseForm.getLsOpsName());
                licenseDetail.setLsOpsPhone(licenseForm.getLsOpsPhone());
                licenseDetail.setLsStatus(ApplicationConstant.STATUC_ACTIVE);
                licenseDetail.setLsreason(licenseForm.getLsregenerationReason());

                // code merging is pending
                detail.setLsStatus(ApplicationConstant.STATUC_INACTIVE);
                detail.setUpdatedBy(userId);
                detail.setLsCost(BigDecimal.valueOf(Double.parseDouble(licenseForm.getLsCost())));
                detail.setLsModelName(licenseForm.getLsmodelName());
                detail.setLsModelNumber(licenseForm.getLsmodelNumber());
                detail.setLsOpsEmail(licenseForm.getLsOpsEmail());
                detail.setLsOpsName(licenseForm.getLsOpsName());
                detail.setLsOpsPhone(licenseForm.getLsOpsPhone());
                detail.setLsreason(licenseForm.getLsregenerationReason());
                customer.getLicenseDetails().add(licenseDetail);
                customerDao.updateCustomer(customer);

            } else {
                detail.setUpdatedBy(userId);
                detail.setLsCost(BigDecimal.valueOf(Double.parseDouble(licenseForm.getLsCost())));
                String macAddress = licenseForm.getLsmacAddress().replaceAll("..(?!$)", "$0:");
                detail.setLsCategory(licenseForm.getLsCategory());
                detail.setLsMacAddress(macAddress);
                detail.setLsModelName(licenseForm.getLsmodelName());
                detail.setLsModelNumber(licenseForm.getLsmodelNumber());
                detail.setLsOpsEmail(licenseForm.getLsOpsEmail());
                detail.setLsOpsName(licenseForm.getLsOpsName());
                detail.setLsOpsPhone(licenseForm.getLsOpsPhone());
                detail.setLsStatus(ApplicationConstant.STATUC_ACTIVE);
                detail.setLsreason(licenseForm.getLsregenerationReason());
                licenseDao.updateLicense(detail);
            }
        } else {
            throw new ApplicationException(ErrorCodesConstants.INVALID_INPUT_CODE,
                    ErrorCodesConstants.INVALID_INPUT);
        }
    } catch (ApplicationException e) {
        LOGGER.error("During updating License exception occured " + e.getMessage());
        throw new ApplicationException(e.getCode(), e.getMessage(), e);
    } catch (Exception e) {
        LOGGER.error("During updating License Exception occured ");
        throw new ApplicationException(ErrorCodesConstants.INTERNAL_SYSTEM_ERROR_CODE,
                ErrorCodesConstants.INTERNAL_SYSTEM_ERROR, e);
    }
    return customer;
}

From source file:cn.hanbell.erp.ejb.PurvdrBean.java

@Override
public Boolean initByOAPSN(String psn) {
    details.put(purvdrBuyerBean, purvdrBuyerList);
    details.put(miscodeBean, miscodeAdded);
    details.put(invwhBean, invwhAdded);/*ww w.j  av a  2  s  .c  o  m*/
    details.put(invwhclkBean, invwhclkAdded);
    HKCG016 oa = beanHKCG016.findByPSN(psn);
    if (oa == null) {
        throw new NullPointerException();
    }

    Purvdr erp = new Purvdr();

    String facno, code, newvdrno;
    switch (oa.getFacno()) {
    //SHB?SHB
    case "C":
    case "G":
    case "J":
    case "N":
    case "C4":
        facno = "C";
        code = "S";
        break;
    default:
        facno = oa.getFacno();
        code = facno;
    }
    //????
    setCompany(facno);
    Purvdr e = this.findByVdrds(oa.getVdrds());
    if (e != null) {
        oa.setVdrno(e.getVdrno());
        beanHKCG016.update(oa);
        return true;
    }

    Miscode m;
    this.miscodeBean.setCompany(facno);
    //m = miscodeBean.findByCdesc(oa.getTtbankna());
    m = miscodeBean.findByCkindAndCdesc("NB", oa.getTtbankna());
    if (m == null) {
        m = new Miscode("NB", miscodeBean.getFormId("NB", "B", 4));
        m.setCdesc(oa.getTtbankna());
        m.setStatus('Y');
        m.setMascreyn('N');
        m.setCusds(oa.getTtbankna());
        miscodeBean.persist(m);
    }

    erp.setVdrna(oa.getVdrna());
    if (oa.getVdrsta() != null && !oa.getVdrsta().equals("")) {
        erp.setVdrsta(oa.getVdrsta().charAt(0));
    }
    erp.setVdrds(oa.getVdrds());
    erp.setVdrdse(oa.getVdrdse());
    erp.setAddress(oa.getAddress());
    if (oa.getDecode() != null && !oa.getDecode().equals("")) {
        erp.setDecode(oa.getDecode().charAt(0));
    }
    erp.setZonenum(oa.getZonenum());
    erp.setCoin(oa.getCoin());
    erp.setTax(oa.getTax());
    if (oa.getTaxrate() != null && !oa.getTaxrate().equals("")) {
        erp.setTaxrate(BigDecimal.valueOf(Double.parseDouble(oa.getTaxrate())));
    }
    erp.setUniform(oa.getUniform());
    erp.setPurkind(oa.getPurkind());
    erp.setTermcode(oa.getTermcode());
    erp.setAreacode(oa.getAreacode());
    if (oa.getPaycom() != null && !oa.getPaycom().equals("")) {
        erp.setPaycom(oa.getPaycom().charAt(0));
    }
    erp.setCuycode(oa.getCuycode());
    if (oa.getPaycode() != null && !oa.getPaycode().equals("")) {
        erp.setPaycode(oa.getPaycode().charAt(0));
    }
    if (oa.getTickdays() != null && !oa.getTickdays().equals("")) {
        erp.setTickdays(Short.valueOf(oa.getTickdays()));
    }
    erp.setBoss(oa.getBoss());
    erp.setMark1(oa.getMark1());
    erp.setSndcode(oa.getSndcode());
    erp.setContactman(oa.getContactman());
    erp.setTtbankno(m.getMiscodePK().getCode());
    erp.setTtbankna(oa.getTtbankna());
    erp.setTtbanknum(oa.getTtbanknum());
    erp.setTtname(oa.getTtname());
    if (oa.getYeramt() != null && !oa.getYeramt().equals("")) {
        erp.setYeramt(BigDecimal.valueOf(Double.parseDouble(oa.getYeramt())));
    }
    if (oa.getCapamt() != null && !oa.getCapamt().equals("")) {
        erp.setCapamt(BigDecimal.valueOf(Double.parseDouble(oa.getCapamt())));
    }
    erp.setTel1(oa.getTel1());
    erp.setTel2(oa.getTel2());
    erp.setWebsite(oa.getWebsite());
    if (oa.getAbccode() != null && !oa.getAbccode().equals("")) {
        erp.setAbccode(oa.getAbccode().charAt(0));
    }
    erp.setFax1(oa.getFax1());
    erp.setFax2(oa.getFax2());
    erp.setBegdate(oa.getBegdate());
    erp.setLatdate(oa.getLatdate());
    erp.setTitle(oa.getTitle());
    erp.setFkfs(oa.getFktype());
    erp.setPaysepcode('1');
    erp.setHandays1((short) 30);

    //??
    newvdrno = getFormId(BaseLib.getDate(), code + erp.getCuycode(), null, 5, "purvdr", "vdrno");
    erp.setVdrno(newvdrno);

    //?
    PurvdrBuyer b = new PurvdrBuyer(facno, "1", newvdrno);
    b.setBuyer(oa.getUserno());

    //?
    if ("Y".equals(oa.getIsvdrwareh())) {
        Invwh w = new Invwh();
        w.setFacno(facno);
        w.setProno("1");
        w.setWareh("JT" + newvdrno);
        if (erp.getVdrna().length() < 3) {
            w.setWhdsc("-" + erp.getVdrna());
        } else {
            //?????
            if (erp.getVdrna().length() <= 4) {
                w.setWhdsc("-" + erp.getVdrna().substring(2));
            } else if (erp.getVdrna().length() > 4) {
                w.setWhdsc("-" + erp.getVdrna().substring(2, 4));
            }

        }
        w.setMrpco('N');
        w.setCostyn('Y');
        w.setWclerk(oa.getJtwareher());
        w.setIndate(BaseLib.getDate());
        w.setUserno("mis");
        invwhAdded.add(w);

        //?
        Invwhclk u = new Invwhclk(w.getFacno(), w.getProno(), w.getWareh(), w.getWclerk());
        u.setMainyn('Y');
        u.setIndate(BaseLib.getDate());
        u.setUserno("mis");
        invwhclkAdded.add(u);
    }

    //?MISCODE
    Miscode c = new Miscode("PJ", newvdrno);
    c.setCdesc(erp.getVdrna());
    c.setStatus('Y');
    c.setMascreyn('Y');
    c.setCusds(erp.getVdrds());

    purvdrBuyerList.add(b);
    miscodeAdded.add(c);

    try {
        persist(erp, details);
        getEntityManager().flush();

        oa.setVdrno(newvdrno);
        beanHKCG016.update(oa);

        switch (oa.getFacno()) {
        case "G":
            //?ERP
            resetFacno("G");
            syncGZBean.persist(erp, details);
            syncGZBean.getEntityManager().flush();
            break;
        case "J":
            //??ERP
            resetFacno("J");
            syncJNBean.persist(erp, details);
            syncJNBean.getEntityManager().flush();
            break;
        case "N":
            //??ERP
            resetFacno("N");
            syncNJBean.persist(erp, details);
            syncNJBean.getEntityManager().flush();
            break;
        case "C4":
            //??ERP
            resetFacno("C4");
            syncCQBean.persist(erp, details);
            syncCQBean.getEntityManager().flush();
            break;
        default:
        }
        return true;
    } catch (Exception ex) {
        Logger.getLogger(PurvdrBean.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } finally {
        resetObjects();
    }

}