Example usage for java.math BigDecimal floatValue

List of usage examples for java.math BigDecimal floatValue

Introduction

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

Prototype

@Override
public float floatValue() 

Source Link

Document

Converts this BigDecimal to a float .

Usage

From source file:fixio.fixprotocol.fields.FieldFactoryTest.java

@Test
public void testValueOfFloat() throws Exception {
    BigDecimal value = BigDecimal.valueOf(new Random().nextInt()).movePointLeft(5);

    FloatField field = FieldFactory.valueOf(FieldType.SettlCurrFxRate.tag(),
            value.toPlainString().getBytes(US_ASCII));

    assertEquals("tagnum", FieldType.SettlCurrFxRate.tag(), field.getTagNum());
    assertEquals("value", value.doubleValue(), field.getValue().doubleValue(), 0.0);
    assertEquals("value", value.floatValue(), field.floatValue(), 0.0);

}

From source file:com.ugam.collage.plus.service.people_count.impl.TeamStructureServiceImpl.java

@Override
public PCTeamStructureVo getMgrTeamData(Integer yearId, Integer monthId, String costCentreId,
        Integer mgrEmployeeId) {//from   w  w w  .  j av a  2 s.  c o m

    Map<Integer, List<Integer>> assignedEmployees = new HashMap<Integer, List<Integer>>();
    Set<Integer> selectedProject = new HashSet<Integer>();
    Map<Integer, Integer> employeeRulesVo = new HashMap<Integer, Integer>();
    Set<Integer> selectedClient = new HashSet<Integer>();

    List<EmployeeMonthlyAssignment> emaList = employeeMonthlyAssignmentDao.findByYearMonthCostCenterMgr(yearId,
            monthId, costCentreId, mgrEmployeeId);
    for (EmployeeMonthlyAssignment ema : emaList) {
        if (ema.getEmpFsAccessByTsClosingPickedUpBy() == null) {
            continue;
        }
        Integer ruleId = ema.getEmployeeCntRulesByClosingRuleId() != null
                ? ema.getEmployeeCntRulesByClosingRuleId().getId()
                : null;
        Integer employeeId = ema.getEmployeeMaster().getEmployeeId();
        employeeRulesVo.put(employeeId, ruleId);
    }

    List<EmpClientProjectTeamStruct> teamStructure = empClientProjectTeamStructDao.findByYearMonthTypeMgr(
            yearId, monthId, Constants.COUNT_CLASSIFICATION_TYPE_CLOSING, mgrEmployeeId);
    for (EmpClientProjectTeamStruct struct : teamStructure) {
        ProjectMaster projectMaster = struct.getProjectMaster();
        Integer projectId = projectMaster.getProjectId();
        selectedProject.add(projectId);
        Integer companyId = projectMaster.getCompanyMaster().getCompanyId();
        selectedClient.add(companyId);

        List<Integer> projectList = assignedEmployees.get(projectId);
        if (projectList == null) {
            projectList = new ArrayList<Integer>();
            assignedEmployees.put(projectId, projectList);
        }
        projectList.add(struct.getEmployeeMaster().getEmployeeId());
    }

    Set<Integer> selectedEmployees = employeeRulesVo.keySet();

    PCTeamStructureVo teamStructureVo = new PCTeamStructureVo(assignedEmployees,
            new ArrayList<Integer>(selectedProject), employeeRulesVo, new ArrayList<Integer>(selectedClient));
    teamStructureVo.setSelectedEmp(new ArrayList<Integer>(selectedEmployees));

    Map<Integer, Integer> apportionApproachVos = new HashMap<Integer, Integer>();
    List<EmpCntPcApportionApproach> apportionApproachs = empCntPcApportionApproachDao.findByMonth(yearId,
            monthId, mgrEmployeeId, Constants.COUNT_CLASSIFICATION_TYPE_CLOSING);
    for (EmpCntPcApportionApproach apportionApproach : apportionApproachs) {
        apportionApproachVos.put(apportionApproach.getEmployeeMaster().getEmployeeId(),
                apportionApproach.getApportionApproach());
    }
    teamStructureVo.setApportionApproachs(apportionApproachVos);

    Map<Integer, Map<String, Float>> proportionVos = new HashMap<Integer, Map<String, Float>>();

    List<EmployeePcTagsTeamStruct> employeePcTagsTeamStructs = employeePcTagsTeamStructDao.findByMonth(yearId,
            monthId, mgrEmployeeId, Constants.COUNT_CLASSIFICATION_TYPE_CLOSING);
    for (EmployeePcTagsTeamStruct employeePcTagsTeamStruct : employeePcTagsTeamStructs) {
        int employeeId = employeePcTagsTeamStruct.getEmployeeMaster().getEmployeeId();
        Map<String, Float> employeeMap = proportionVos.get(employeeId);
        if (employeeMap == null) {
            employeeMap = new HashMap<String, Float>();
            proportionVos.put(employeeId, employeeMap);
        }
        BigDecimal pcProportion = employeePcTagsTeamStruct.getProportion();
        String profitCentreId = employeePcTagsTeamStruct.getProfitCentre().getProfitCentreId();
        employeeMap.put(profitCentreId, pcProportion.floatValue());
    }

    teamStructureVo.setProportions(proportionVos);
    return teamStructureVo;
}

From source file:com.salesmanager.core.service.ws.impl.SalesManagerInvoiceWSImpl.java

/**
 * processNewInvoice method processes the create invoice logic
 * and sets the newly created invoice-id and OrderTotal to response.
 * @param invoice {@link Invoice}/* ww w  .ja  va  2s  . c om*/
 * @param messageSource {@link MessageSource}
 * @param locale {@link Locale}
 * @param response {@link CreateInvoiceWebServiceResponse}
 * @throws Exception 
 */
private CreateInvoiceWebServiceResponse processNewInvoice(int merchantId, Invoice invoice,
        MessageSource messageSource, Locale locale, CreateInvoiceWebServiceResponse response) throws Exception {
    //Generate an id
    SystemService sservice = (SystemService) ServiceFactory.getService(ServiceFactory.SystemService);
    long nextOrderId = sservice.getNextOrderIdSequence();

    Order order = new Order();
    order.setChannel(OrderConstants.INVOICE_CHANNEL);
    SimpleDateFormat format = new SimpleDateFormat(Constants.DATE_FORMAT);
    order.setDatePurchased(format.parse(invoice.getDate()));
    order.setOrderDateFinished(format.parse(invoice.getDueDate()));
    order.setOrderId(nextOrderId);
    order.setMerchantId(merchantId);
    order.setCurrency(invoice.getCurrency());

    //create customer info
    CustomerService cservice = (CustomerService) ServiceFactory.getService(ServiceFactory.CustomerService);
    Customer customer = cservice.getCustomer(invoice.getCustomerId());

    order.setCustomerName(customer.getCustomerFirstname() + " " + customer.getCustomerLastname());
    order.setCustomerStreetAddress(customer.getCustomerStreetAddress());
    order.setCustomerCity(customer.getCustomerBillingCity());
    order.setCustomerPostcode(customer.getCustomerPostalCode());
    Map countries = RefCache.getAllcountriesmap(1);//default language 
    Country country = (Country) countries.get(customer.getCustomerCountryId());
    order.setCustomerCountry(country.getCountryName());

    Map zones = RefCache.getAllZonesmap(LanguageUtil.getLanguageNumberCode(invoice.getLanguage()));
    Zone zone = (Zone) zones.get(customer.getCustomerZoneId());
    order.setCustomerTelephone(customer.getCustomerTelephone());
    if (zone != null) {
        order.setCustomerState(zone.getZoneName());
    }

    MerchantService mservice = (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);
    MerchantStore store = mservice.getMerchantStore(order.getMerchantId());
    //create products info
    List<OrderProduct> products = new ArrayList<OrderProduct>();
    //for each product
    if (invoice.getProducts() != null) {
        for (Product product : invoice.getProducts()) {
            OrderProduct orderProduct = com.salesmanager.core.util.CheckoutUtil
                    .createOrderProduct(product.getProductId(), locale, order.getCurrency());
            orderProduct.setProductQuantity(product.getQuantity());
            if (product.isOverWritePrice()) {
                orderProduct.setProductPrice(new BigDecimal(product.getPrice()));
            }

            List<OrderProductAttribute> orderProductAttrbutes = new ArrayList<OrderProductAttribute>();
            if (product.getAttributes() != null) {
                for (Attribute attribute : product.getAttributes()) {
                    OrderProductAttribute opa = new OrderProductAttribute();
                    opa.setProductOptionValueId(attribute.getAttributeId());
                    opa.setPrice(String.valueOf(attribute.getPrice()));
                    orderProductAttrbutes.add(opa);
                }
            }
            CheckoutUtil.addAttributesToProduct(orderProductAttrbutes, orderProduct, order.getCurrency(),
                    locale);
            products.add(orderProduct);
        }
    }

    OrderService oservice = (OrderService) ServiceFactory.getService(ServiceFactory.OrderService);

    Shipping shipping = null;

    if (invoice.isCalculateShipping()) {

        boolean hasShipping = false;
        for (Object o : products) {
            OrderProduct op = (OrderProduct) o;
            if (op.isShipping()) {
                hasShipping = true;
                break;
            }
        }

        ShippingService shippingService = (ShippingService) ServiceFactory
                .getService(ServiceFactory.ShippingService);
        ShippingInformation shippingInformation = shippingService.getShippingQuote(products, customer,
                merchantId, locale, invoice.getCurrency());

        ShippingOption retainedOption = null;

        Collection methods = shippingInformation.getShippingMethods();
        //take less expensive
        for (Object o : methods) {
            ShippingMethod method = (ShippingMethod) o;//shipping carrier
            Collection options = method.getOptions();
            for (Object opt : options) {
                ShippingOption option = (ShippingOption) opt;
                BigDecimal price = option.getOptionPrice();
                if (retainedOption == null) {
                    retainedOption = option;
                } else {
                    if (price.floatValue() < retainedOption.getOptionPrice().floatValue()) {
                        retainedOption = option;
                    }
                }
            }
        }

        if (retainedOption != null) {

            shipping = new Shipping();
            shipping.setHandlingCost(shippingInformation.getHandlingCost());
            shipping.setShippingCost(retainedOption.getOptionPrice());
            shipping.setShippingModule(retainedOption.getModule());
            shipping.setShippingDescription(retainedOption.getDescription());
        }
    }

    OrderTotalSummary summary = oservice.calculateTotal(order, products, customer, shipping,
            order.getCurrency(), locale);
    Map totals = OrderUtil.getOrderTotals(order.getOrderId(), summary, order.getCurrency(), locale);
    HashSet s = new HashSet(totals.entrySet());
    order.setOrderProducts(new HashSet(products));
    order.setOrderTotal(s);
    order.setTotal(summary.getTotal());
    order.setOrderTax(summary.getTaxTotal());
    //save invoice 
    oservice.saveInvoice(merchantId, order.getOrderId(), order.getDatePurchased(), order.getOrderDateFinished(),
            "", false, products, customer, shipping, store, locale);

    response.setInvoiceId(order.getOrderId());

    //Return order totals in response.
    Order createdOrder = oservice.getOrder(order.getOrderId());
    List<com.salesmanager.core.entity.orders.ws.OrderTotal> orderTotalList = new ArrayList<com.salesmanager.core.entity.orders.ws.OrderTotal>();
    for (OrderTotal orderTotal : createdOrder.getOrderTotal()) {
        com.salesmanager.core.entity.orders.ws.OrderTotal responseOrderTotal = new com.salesmanager.core.entity.orders.ws.OrderTotal();
        BeanUtils.copyProperties(responseOrderTotal, orderTotal);
        orderTotalList.add(responseOrderTotal);
    }

    response.setOrderTotals(orderTotalList.toArray(new com.salesmanager.core.entity.orders.ws.OrderTotal[] {}));
    return response;
}

From source file:org.kuali.kfs.module.purap.service.PurapAccountingServiceTest.java

/**
 * Used by tests of generateAccountDistributionForProration and related methods to make comparisons between
 * the percentages given by the resulting distributed accounts and the percentages that we think should be
 * correct for those lines./*  ww w.j a v  a2 s .co m*/
 * 
 * @param distributedAccounts       A List of the PurApAccountingLines that result from the distribution to be tested.
 * @param correctPercents           A List of percents we think should be correct, in BigDecimal format
 */
private void comparePercentages(List<PurApAccountingLine> distributedAccounts,
        List<BigDecimal> correctPercents) {
    for (int i = 0; i < distributedAccounts.size(); i++) {
        PurApAccountingLine line = distributedAccounts.get(i);
        BigDecimal percent = line.getAccountLinePercent();
        assertTrue(percent.floatValue() == correctPercents.get(i).floatValue());
    }
}

From source file:jgnash.ui.report.compiled.IncomeExpensePieChart.java

private PieDataset createPieDataSet(Account a) {
    DefaultPieDataset returnValue = new DefaultPieDataset();
    if (a != null) {

        BigDecimal total = a.getTreeBalance(startField.getLocalDate(), endField.getLocalDate(),
                a.getCurrencyNode());/* ww w  . j  a v a  2s .  co  m*/

        // abs() on all values won't work if children aren't of uniform sign,
        // then again, this chart is not right to display those trees
        boolean negate = total != null && total.floatValue() < 0;

        // accounts may have balances independent of their children
        BigDecimal value = a.getBalance(startField.getLocalDate(), endField.getLocalDate());

        if (value.compareTo(BigDecimal.ZERO) != 0) {
            returnValue.setValue(a, negate ? value.negate() : value);
        }

        for (final Account child : a.getChildren(Comparators.getAccountByCode())) {
            value = child.getTreeBalance(startField.getLocalDate(), endField.getLocalDate(),
                    a.getCurrencyNode());

            if (showEmptyCheck.isSelected() || value.compareTo(BigDecimal.ZERO) != 0) {
                returnValue.setValue(child, negate ? value.negate() : value);
            }
        }
    }
    return returnValue;
}

From source file:wm.xmwei.ui.view.indicator.PagerSlidingTabIndicator.java

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    if (isInEditMode() || tabCount == 0) {
        return;//from   ww  w . ja v  a  2 s.c  o  m
    }

    final int height = getHeight();
    final int width = getWidth();

    // draw indicator line

    //rectPaint.setColor(indicatorColor);

    // default: line below current tab
    View currentTab = tabsContainer.getChildAt(currentPosition);
    float lineLeft = currentTab.getLeft();
    float lineRight = currentTab.getRight();

    // if there is an offset, start interpolating left and right coordinates between current and next tab
    if (currentPositionOffset > 0f && currentPosition < tabCount - 1) {

        View nextTab = tabsContainer.getChildAt(currentPosition + 1);
        nextTab.setBackgroundResource(Color.TRANSPARENT);
        final float nextTabLeft = nextTab.getLeft();
        final float nextTabRight = nextTab.getRight();

        lineLeft = (currentPositionOffset * nextTabLeft + (1f - currentPositionOffset) * lineLeft);
        lineRight = (currentPositionOffset * nextTabRight + (1f - currentPositionOffset) * lineRight);
    }

    /*   canvas.drawRect(lineLeft, height - indicatorHeight, lineRight, height, rectPaint);*/

    float center = (lineLeft + lineRight) / 2;

    // ,??  
    // Path path = new Path();
    //path.moveTo(center,height - indicatorHeight);//   

    BigDecimal a = BigDecimal.valueOf(1.736);
    BigDecimal b = BigDecimal.valueOf(3);
    BigDecimal bigDecimal = a.divide(b, BigDecimal.ROUND_HALF_UP);
    float result = bigDecimal.floatValue() * indicatorHeight;

    //path.lineTo(center-result-2, height);  
    // path.lineTo(center+result+2, height);
    //path.close(); // ??  
    // canvas.drawPath(path, rectPaint);

    Path path2 = new Path();
    path2.moveTo(0, 0);//   
    path2.lineTo(0, height);
    path2.lineTo(center - result - 5, height);
    path2.lineTo(center, height - indicatorHeight);
    path2.lineTo(center + result + 5, height);
    path2.lineTo(tabsContainer.getWidth(), height);
    path2.lineTo(tabsContainer.getWidth(), 0);

    path2.close(); // ??  
    canvas.drawPath(path2, bgPaint);
    // draw underline

    /*rectPaint.setColor(underlineColor);
    canvas.drawRect(0, height - underlineHeight, tabsContainer.getWidth(), height, rectPaint);*/

    // draw divider

    /*   dividerPaint.setColor(dividerColor);
       for (int i = 0; i < tabCount - 1; i++) {
          View tab = tabsContainer.getChildAt(i);
          canvas.drawLine(tab.getRight(), dividerPadding, tab.getRight(), height - dividerPadding, dividerPaint);
       }*/
}

From source file:org.openvpms.archetype.rules.doc.DocumentTemplate.java

/**
 * Helper to convert a custom paper size to a {@link MediaSizeName}.
 *
 * @param width  the page width//  w ww .ja  v  a  2  s.  co m
 * @param height the page height
 * @param units  the units. One of 'MM' or 'INCH'.
 * @return the corresponding media size name.
 * @throws DocumentException if the paper size is invalid
 */
private MediaSizeName getMedia(BigDecimal width, BigDecimal height, String units) {
    int unitCode = Units.getUnits(units);
    try {
        return MediaSize.findMedia(width.floatValue(), height.floatValue(), unitCode);
    } catch (IllegalArgumentException exception) {
        String size = width + "x" + height + " " + units;
        throw new DocumentException(InvalidPaperSize, size);
    }
}

From source file:org.kalypso.model.wspm.tuhh.core.wprof.BCEShapeWPRofContentProvider.java

private <T> T toNumber(final BigDecimal in, final Class<T> outType) {
    if (Byte.class == outType)
        return outType.cast(in.byteValue());
    if (Short.class == outType)
        return outType.cast(in.shortValue());
    if (Integer.class == outType)
        return outType.cast(in.intValue());
    if (Long.class == outType)
        return outType.cast(in.longValue());
    if (Float.class == outType)
        return outType.cast(in.floatValue());
    if (Double.class == outType)
        return outType.cast(in.doubleValue());

    if (BigInteger.class == outType)
        return outType.cast(in.toBigInteger());

    return outType.cast(in);
}

From source file:com.salesmanager.central.orders.TransactionDetailsAction.java

/**
 * Process a new transaction, currently supports refund and capture
 * following a pre-authorize/* w w w . j ava2  s .  c  o m*/
 * 
 * @return
 * @throws Exception
 */
public String processTransaction() throws Exception {

    Context ctx = super.getContext();

    MerchantService mservice = (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);
    MerchantStore store = mservice.getMerchantStore(ctx.getMerchantid());

    try {

        if (this.getOrder() == null || this.getOrder().getOrderId() == 0) {
            super.setAuthorizationMessage();
            return "AUTHORIZATIONEXCEPTION";
        }

        prepareOrderDetails();

        /** INPUT VALIDATION **/
        // validate the presence of a transaction type in the request
        // parameter
        if (this.getProcess() == null) {
            log.error(
                    "No transaction process id in request parameter. Require &process=1 or &process=2 or &process=3");
            return SUCCESS;
        }

        int process = -1;
        try {
            process = Integer.parseInt(this.getProcess());
        } catch (NumberFormatException nfe) {
            log.error("Can't parse process id in request parameter [" + this.getProcess()
                    + "],  require &process=1 or &process=2 or &process=3");
            return SUCCESS;
        }

        // process 2 and 3 supported
        if (process < 2 || process > 3) {
            log.error("Transaction process type not supported " + this.getProcess());
            return SUCCESS;
        }

        /** END VALIDATION **/

        PaymentService service = (PaymentService) ServiceFactory.getService(ServiceFactory.PaymentService);

        switch (process) {

        case PaymentConstants.CAPTURE:
            service.captureTransaction(store, this.getOrder());
            break;

        case PaymentConstants.REFUND:

            // get amount

            if (StringUtils.isBlank(this.getRefundAmount())) {
                super.addFieldError("orderTotal", "transaction.error.transactionamount");
                return INPUT;
            }

            BigDecimal originalAmount = this.getOrder().getTotal();

            BigDecimal newAmount = null;
            try {

                newAmount = CurrencyUtil.validateCurrency(this.getRefundAmount(), order.getCurrency());
            } catch (ValidationException e) {
                super.addFieldError("orderTotal", "transaction.error.transactionamount");
                return INPUT;
            }

            if (newAmount == null || newAmount.floatValue() > originalAmount.floatValue()) {
                super.addFieldError("orderTotal", "transaction.error.transactionamounttoohigh");
                return INPUT;
            }

            OrderService oservice = (OrderService) ServiceFactory.getService(ServiceFactory.OrderService);
            oservice.refundOrder(this.getOrder(), newAmount, super.getLocale());

            break;

        default:
            log.error("Transaction process type not supported " + this.getProcess());
            MessageUtil.addErrorMessage(super.getServletRequest(),
                    LabelUtil.getInstance().getText("errors.technical"));

        }

        super.setSuccessMessage();

    } catch (AuthorizationException ae) {
        super.setAuthorizationMessage();
        return "AUTHORIZATIONEXCEPTION";
    } catch (Exception e) {
        if (e instanceof TransactionException) {
            TransactionException te = (TransactionException) e;
            // Display appropriate message to end user
            if (te.getErrorcode() != null && !te.getErrorcode().trim().equals("")) {
                String textkey = "transaction.errors." + te.getErrorcode();
                if (te.getReason() != null && !te.getReason().trim().equals("")) {
                    MessageUtil.addErrorMessage(super.getServletRequest(),
                            LabelUtil.getInstance().getText(textkey) + " [" + te.getReason() + "]");
                } else {
                    MessageUtil.addErrorMessage(super.getServletRequest(),
                            LabelUtil.getInstance().getText(textkey));
                }
            } else {
                MessageUtil.addErrorMessage(super.getServletRequest(),
                        te.getMessage() + " [" + te.getErrorcode() + "]");
                //super.setTechnicalMessage();
            }
        } else {
            log.error(e);
            super.setTechnicalMessage();
        }
    }

    return SUCCESS;
}

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;
            }/*from  ww w . jav  a2s .  co  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;
}