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:com.streamsets.pipeline.stage.it.DecimalTypeIT.java

@Test
public void incompatiblePrecision() throws Exception {
    executeUpdate("CREATE TABLE `tbl` (id int, dec decimal(4, 2)) PARTITIONED BY (dt string) STORED AS AVRO");

    HiveMetadataProcessor processor = new HiveMetadataProcessorBuilder().decimalConfig(4, 2).build();
    HiveMetastoreTarget hiveTarget = new HiveMetastoreTargetBuilder().build();

    List<Record> records = new LinkedList<>();

    Map<String, Field> map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 1));
    map.put("dec", Field.create(BigDecimal.valueOf(12345)));
    Record record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);/*w  ww .j a v a2  s .  c o m*/

    try {
        processRecords(processor, hiveTarget, records);
        Assert.fail("Expected failure!");
    } catch (OnRecordErrorException e) {
        Assert.assertEquals(Errors.HIVE_26, e.getErrorCode());
        Assert.assertTrue(e.getMessage().contains("precision 5 is more then expected 4"));
    }
}

From source file:Main.java

/**
 * Compute the integral root of x to a given scale, x >= 0.
 * Use Newton's algorithm.//from  w w w . j  av a  2  s  . c o m
 * @param x the value of x
 * @param index the integral root value
 * @param scale the desired scale of the result
 * @return the result value
 */
public static BigDecimal intRoot(BigDecimal x, long index, int scale) {
    // Check that x >= 0.
    if (x.signum() < 0) {
        throw new IllegalArgumentException("x < 0");
    }

    int sp1 = scale + 1;
    BigDecimal n = x;
    BigDecimal i = BigDecimal.valueOf(index);
    BigDecimal im1 = BigDecimal.valueOf(index - 1);
    BigDecimal tolerance = BigDecimal.valueOf(5).movePointLeft(sp1);
    BigDecimal xPrev;

    // The initial approximation is x/index.
    x = x.divide(i, scale, BigDecimal.ROUND_HALF_EVEN);

    // Loop until the approximations converge
    // (two successive approximations are equal after rounding).
    do {
        // x^(index-1)
        BigDecimal xToIm1 = intPower(x, index - 1, sp1);

        // x^index
        BigDecimal xToI = x.multiply(xToIm1).setScale(sp1, BigDecimal.ROUND_HALF_EVEN);

        // n + (index-1)*(x^index)
        BigDecimal numerator = n.add(im1.multiply(xToI)).setScale(sp1, BigDecimal.ROUND_HALF_EVEN);

        // (index*(x^(index-1))
        BigDecimal denominator = i.multiply(xToIm1).setScale(sp1, BigDecimal.ROUND_HALF_EVEN);

        // x = (n + (index-1)*(x^index)) / (index*(x^(index-1)))
        xPrev = x;
        x = numerator.divide(denominator, sp1, BigDecimal.ROUND_DOWN);

        Thread.yield();
    } while (x.subtract(xPrev).abs().compareTo(tolerance) > 0);

    return x;
}

From source file:com.oncore.calorders.rest.service.extension.OrderHistoryFacadeRESTExtension.java

/**
 * Creates an order, containing the ordered products and related services.
 *
 * @param orderjson The order, represented as a JSON string
 * @throws DataAccessException/*from w  ww  . j ava  2  s. c o  m*/
 */
@POST
@Path("createOrder")
@Consumes({ MediaType.APPLICATION_JSON })
public void createOrder(String orderjson) throws DataAccessException {

    try {
        JsonReader reader = Json.createReader(new StringReader(orderjson));
        JsonObject orderObject = reader.readObject();
        reader.close();

        OrderHistory order = new OrderHistory();

        order.setUpdateTs(new Date());
        order.setUpdateUserId(orderObject.getString("updateUserId", null));
        order.setCreateTs(new Date());
        order.setCreateUserId(orderObject.getString("createUserId", null));

        OrdStatusCd ordStatusCd = this.ordStatusCdFacadeREST.find(orderObject.getString("orderStatusCd", null));

        if (ordStatusCd == null) {
            throw new DataAccessException(ErrorCode.DATAACCESSERROR.toString());
        } else {
            order.setOrdStatusCd(ordStatusCd);
        }

        Party party = this.partyFacadeRESTExtension.find(Integer.valueOf(orderObject.getString("partyUid")));

        if (party == null) {
            throw new DataAccessException(ErrorCode.DATAACCESSERROR.toString());
        } else {
            order.setPtyUidFk(party);

            order.setDepUidFk(
                    party.getGroupPartyAssocCollection().iterator().next().getGrpUidFk().getDepUidFk());
        }

        order.setOrderProductAssocCollection(new ArrayList<OrderProductAssoc>());

        JsonArray productList = orderObject.getJsonArray("products");

        for (int i = 0; i < productList.size(); i++) {
            JsonObject productObject = productList.getJsonObject(i);
            OrderProductAssoc orderProductAssoc = new OrderProductAssoc();

            Product product = this.productFacadeRESTExtension.find(productObject.getInt("prdUid"));

            orderProductAssoc.setPrdUidFk(product);
            orderProductAssoc.setOrdUidFk(order);
            orderProductAssoc.setUpdateTs(new Date());
            orderProductAssoc.setUpdateUserId(productObject.getString("updateUserId", null));
            orderProductAssoc.setCreateTs(new Date());
            orderProductAssoc.setCreateUserId(productObject.getString("createUserId", null));
            orderProductAssoc.setOpaQuantity(productObject.getInt("quantity"));
            orderProductAssoc.setOpaPrice(product.getPrdCntrUnitPrice()
                    .multiply(BigDecimal.valueOf(productObject.getInt("quantity"))));

            order.getOrderProductAssocCollection().add(orderProductAssoc);
        }

        super.create(order);
    } catch (Exception ex) {
        Logger.error(LOG, FormatHelper.getStackTrace(ex));
        throw new DataAccessException(ex, ErrorCode.DATAACCESSERROR);
    }

}

From source file:de.hybris.platform.refund.RefundServiceTest.java

@Test
public void testRefundCalculation() throws Exception {
    final ProductModel product1 = new ProductModel();
    product1.setCode("test");
    product1.setUnit(productService.getUnit("kg"));
    product1.setCatalogVersion(catalogService.getCatalogVersion("testCatalog", "Online"));
    //product1.setPrice(Double.valueOf(100));

    final PriceRowModel prmodel = modelService.create(PriceRowModel.class);
    prmodel.setCurrency(i18nService.getCurrency("EUR"));
    prmodel.setMinqtd(Long.valueOf(1));
    prmodel.setNet(Boolean.TRUE);
    prmodel.setPrice(Double.valueOf(5.00));
    prmodel.setUnit(productService.getUnit("kg"));
    prmodel.setProduct(product1);//  w  ww .j a  v  a2 s  .  c om
    prmodel.setCatalogVersion(catalogService.getCatalogVersion("testCatalog", "Online"));
    modelService.saveAll(Arrays.asList(prmodel, product1));

    final CartModel cart = cartService.getSessionCart();
    final UserModel user = userService.getCurrentUser();
    cartService.addToCart(cart, product1, 2, null);

    final AddressModel deliveryAddress = new AddressModel();
    deliveryAddress.setOwner(user);
    deliveryAddress.setFirstname("Juergen");
    deliveryAddress.setLastname("Albertsen");
    deliveryAddress.setTown("Muenchen");
    modelService.saveAll(Arrays.asList(deliveryAddress));

    final DebitPaymentInfoModel paymentInfo = new DebitPaymentInfoModel();
    paymentInfo.setOwner(cart);
    paymentInfo.setCode("debit");
    paymentInfo.setBank("MeineBank");
    paymentInfo.setUser(user);
    paymentInfo.setAccountNumber("34434");
    paymentInfo.setBankIDNumber("1111112");
    paymentInfo.setBaOwner("Ich");
    modelService.saveAll(Arrays.asList(paymentInfo));

    // the original order the customer wants to have a refund for
    final OrderModel order = orderService.placeOrder(cart, deliveryAddress, null, paymentInfo);

    // lets create a RMA for it
    final ReturnRequestModel request = returnService.createReturnRequest(order);
    returnService.createRMA(request);

    // based on the original order the call center agent creates a refund order kind of preview (**)
    final OrderModel refundOrderPreview = refundService.createRefundOrderPreview(order);

    // all following "refund processing", will be based on the refund order instance (copy of the original order)
    final AbstractOrderEntryModel productToRefund1 = refundOrderPreview.getEntries().iterator().next(); // has quantity of 2

    // create the preview "refund"
    final RefundEntryModel refundEntry1 = returnService.createRefund(request, productToRefund1, "no.1",
            Long.valueOf(1), ReturnAction.IMMEDIATE, RefundReason.LATEDELIVERY);

    // calculate the preview refund ...
    assertEquals("Unexpected order price!", BigDecimal.valueOf(10.0),
            BigDecimal.valueOf(refundOrderPreview.getTotalPrice().doubleValue()));

    refundService.apply(Arrays.asList(refundEntry1), refundOrderPreview);

    assertEquals("Wrong refund (preview)!", BigDecimal.valueOf(5.0),
            BigDecimal.valueOf(refundOrderPreview.getTotalPrice().doubleValue()));

    assertNull("There shouldn't exists any record entry yet!",
            ((DefaultRefundService) refundService).getModificationHandler().getReturnRecord(order));
    // based on presented "preview" (see **) the customer decides if he wants to accept the offered refund
    // ... and in the case the customer agrees, the call center agent will now recalculate the "original" order
    refundService.apply(refundOrderPreview, request);

    assertEquals("Wrong refund (apply)!", BigDecimal.valueOf(5.0),
            BigDecimal.valueOf(order.getTotalPrice().doubleValue()));

    final Collection<OrderHistoryEntryModel> histories = orderHistoryService.getHistoryEntries(order, null,
            null);

    assertEquals("Wrong count of history entries!", 1, histories.size());

    final OrderHistoryEntryModel history = histories.iterator().next();

    assertEquals("Unexpected orderhistory price!", BigDecimal.valueOf(10.0),
            BigDecimal.valueOf(history.getPreviousOrderVersion().getTotalPrice().doubleValue()));
}

From source file:net.sourceforge.fenixedu.presentationTier.TagLib.GanttDiagramTagLib.java

private StringBuilder generateGanttDiagramInTimeMode(BigDecimal tableWidth) throws JspException {
    StringBuilder builder = new StringBuilder();

    if (!getEvents().isEmpty()) {
        if (isShowPeriod() && isShowObservations()) {
            builder.append("<table style=\"width:")
                    .append(tableWidth.add(BigDecimal.valueOf(FIXED_COLUMNS_SIZE_EM)))
                    .append("em;\" class=\"tcalendar thlight\">");
        } else {/*  w  w  w  .  jav  a2s. c  om*/
            builder.append("<table class=\"tcalendar thlight\">");
        }

        generateHeaders(builder);

        int numberOfUnits = getNumberOfUnits();

        String selectedEvent = getRequest().getParameter(getEventParameter());
        Object selectedEventObject = getRequest().getAttribute(getEventParameter());

        for (GanttDiagramEvent event : getEvents()) {

            String eventUrl = getRequest().getContextPath() + getEventUrl() + "&amp;" + getEventParameter()
                    + "=" + event.getGanttDiagramEventIdentifier();

            if (event.getGanttDiagramEventUrlAddOns() != null) {
                eventUrl = eventUrl.concat(event.getGanttDiagramEventUrlAddOns());
            }

            final MultiLanguageString diagramEventName = event.getGanttDiagramEventName();
            String eventName = diagramEventName == null ? "" : diagramEventName.getContent();
            String paddingStyle = "padding-left:" + event.getGanttDiagramEventOffset() * PADDING_LEFT_MULTIPLIER
                    + "px";

            if (event.getGanttDiagramEventIdentifier().equals(selectedEvent) || (selectedEventObject != null
                    && event.getGanttDiagramEventIdentifier().equals(selectedEventObject.toString()))) {
                builder.append("<tr class=\"selected\">");
            } else {
                builder.append("<tr>");
            }

            if (getViewTypeEnum() == ViewType.YEAR_DAILY) {
                builder.append("<td class=\"padded\">").append("<div class=\"nowrap\">");
                builder.append("<span style=\"").append(paddingStyle).append("\" title=\"").append(eventName)
                        .append("\">");
                builder.append("<a href=\"").append(eventUrl).append("&amp;month=")
                        .append(Month.values()[event.getGanttDiagramEventMonth() - 1].toString()).append("\">")
                        .append(eventName);
            } else {
                builder.append("<td class=\"padded\">")
                        .append("<div style=\"overflow:hidden; width: 14.5em;\" class=\"nowrap\">");
                builder.append("<span style=\"").append(paddingStyle).append("\" title=\"").append(eventName)
                        .append("\">");
                builder.append("<a href=\"").append(eventUrl).append("\">").append(eventName);
            }
            builder.append("</a></span></div></td>");

            for (DateTime day : getGanttDiagramObject().getDays()) {

                int startIndex = 0, endIndex = 0;
                int dayOfMonth = day.getDayOfMonth();
                int monthOfYear = day.getMonthOfYear();
                if (getViewTypeEnum() == ViewType.YEAR_DAILY) {
                    monthOfYear = event.getGanttDiagramEventMonth();
                }
                int year = day.getYear();
                YearMonthDay yearMonthDay = new YearMonthDay(year, monthOfYear, 1);

                isEventToMarkWeekendsAndHolidays = event.isGanttDiagramEventToMarkWeekendsAndHolidays();

                if (!isEventToMarkWeekendsAndHolidays) {
                    builder.append("<td style=\"width: ").append(convertToEm(numberOfUnits))
                            .append("em;\"><div style=\"position: relative;\">");
                }

                if (getViewTypeEnum() == ViewType.YEAR_DAILY) {
                    if (dayOfMonth > yearMonthDay.plusMonths(1).minusDays(1).getDayOfMonth()) {
                        addEmptyDiv(builder);
                        builder.append("</div></td>");
                        continue;
                    }
                }

                specialDiv = false;

                for (Interval interval : event.getGanttDiagramEventSortedIntervals()) {

                    toWrite = null;
                    toMark = true;
                    LocalDate localDate = yearMonthDay.withDayOfMonth(dayOfMonth).toLocalDate();
                    if ((event.getGanttDiagramEventDayType(interval) == DayType.SPECIFIC_DAYS)
                            || (event.getGanttDiagramEventDayType(interval) == DayType.WORKDAY)) {
                        if ((localDate.getDayOfWeek() == SATURDAY_IN_JODA_TIME)
                                || (localDate.getDayOfWeek() == SUNDAY_IN_JODA_TIME)
                                || (Holiday.isHoliday(localDate))) {
                            toMark = false;
                        }
                    }
                    if (isEventToMarkWeekendsAndHolidays) {
                        if (Holiday.isHoliday(localDate)) {
                            toWrite = F;
                        } else if (localDate.getDayOfWeek() == SATURDAY_IN_JODA_TIME) {
                            toWrite = S;
                        } else if (localDate.getDayOfWeek() == SUNDAY_IN_JODA_TIME) {
                            toWrite = D;
                        }
                    }

                    if (interval.getStart().getYear() <= year && interval.getEnd().getYear() >= year) {

                        if (interval.getStart().getYear() < year && interval.getEnd().getYear() > year) {
                            addSpecialDiv(builder, convertToEm(numberOfUnits), EMPTY_UNIT);
                        }
                        // Started in same year and Ended after
                        else if (interval.getStart().getYear() == year && interval.getEnd().getYear() > year) {

                            if (interval.getStart().getMonthOfYear() < monthOfYear) {
                                addSpecialDiv(builder, convertToEm(numberOfUnits), EMPTY_UNIT);

                            } else if (interval.getStart().getMonthOfYear() == monthOfYear) {

                                if (interval.getStart().getDayOfMonth() == dayOfMonth) {
                                    startIndex = calculateTimeOfDay(interval.getStart());
                                    addSpecialDiv(builder, convertToEm(numberOfUnits - (startIndex - 1)),
                                            convertToEm(startIndex - 1));

                                } else if (interval.getStart().getDayOfMonth() < dayOfMonth) {
                                    addSpecialDiv(builder, convertToEm(numberOfUnits), EMPTY_UNIT);
                                }
                            }
                        }
                        // Ended in same year and started before
                        else if (interval.getStart().getYear() < year && interval.getEnd().getYear() == year) {

                            if (interval.getEnd().getMonthOfYear() > monthOfYear) {
                                addSpecialDiv(builder, convertToEm(numberOfUnits), EMPTY_UNIT);

                            } else if (interval.getEnd().getMonthOfYear() == monthOfYear) {

                                if (interval.getEnd().getDayOfMonth() > dayOfMonth) {
                                    addSpecialDiv(builder, convertToEm(numberOfUnits), EMPTY_UNIT);

                                } else if (interval.getEnd().getDayOfMonth() == dayOfMonth) {
                                    endIndex = calculateTimeOfDay(interval.getEnd());
                                    addSpecialDiv(builder, convertToEm(endIndex), EMPTY_UNIT);
                                }
                            }
                        }
                        // Ended and Started In Same Year
                        else if (interval.getStart().getYear() == year && interval.getEnd().getYear() == year) {

                            if (interval.getStart().getMonthOfYear() <= monthOfYear
                                    && interval.getEnd().getMonthOfYear() >= monthOfYear) {

                                if (interval.getStart().getMonthOfYear() == monthOfYear
                                        && interval.getEnd().getMonthOfYear() > monthOfYear) {

                                    if (interval.getStart().getDayOfMonth() == dayOfMonth) {
                                        startIndex = calculateTimeOfDay(interval.getStart());
                                        addSpecialDiv(builder, convertToEm(numberOfUnits - (startIndex - 1)),
                                                convertToEm(startIndex - 1));

                                    } else if (interval.getStart().getDayOfMonth() < dayOfMonth) {
                                        addSpecialDiv(builder, convertToEm(numberOfUnits), EMPTY_UNIT);
                                    }

                                } else if (interval.getStart().getMonthOfYear() < monthOfYear
                                        && interval.getEnd().getMonthOfYear() == monthOfYear) {

                                    if (interval.getEnd().getDayOfMonth() > dayOfMonth) {
                                        addSpecialDiv(builder, convertToEm(numberOfUnits), EMPTY_UNIT);

                                    } else if (interval.getEnd().getDayOfMonth() == dayOfMonth) {
                                        endIndex = calculateTimeOfDay(interval.getEnd());
                                        addSpecialDiv(builder, convertToEm(endIndex), EMPTY_UNIT);
                                    }

                                } else if (interval.getStart().getMonthOfYear() < monthOfYear
                                        && interval.getEnd().getMonthOfYear() > monthOfYear) {
                                    addSpecialDiv(builder, convertToEm(numberOfUnits), EMPTY_UNIT);

                                } else if (interval.getStart().getMonthOfYear() == monthOfYear
                                        && interval.getEnd().getMonthOfYear() == monthOfYear) {

                                    if (interval.getStart().getDayOfMonth() <= dayOfMonth
                                            && interval.getEnd().getDayOfMonth() >= dayOfMonth) {

                                        if (event.isGanttDiagramEventIntervalsLongerThanOneDay()
                                                && (interval.getStart().getDayOfMonth() == dayOfMonth
                                                        || interval.getEnd().getDayOfMonth() > dayOfMonth)) {
                                            startIndex = calculateTimeOfDay(interval.getStart());
                                            addSpecialDiv(builder,
                                                    convertToEm(numberOfUnits - (startIndex - 1)),
                                                    convertToEm(startIndex - 1));
                                        } else if (interval.getStart().getDayOfMonth() == dayOfMonth
                                                && interval.getEnd().getDayOfMonth() > dayOfMonth) {
                                            startIndex = calculateTimeOfDay(interval.getStart());
                                            addSpecialDiv(builder,
                                                    convertToEm(numberOfUnits - (startIndex - 1)),
                                                    convertToEm(startIndex - 1));
                                        }

                                        else if (interval.getStart().getDayOfMonth() < dayOfMonth
                                                && interval.getEnd().getDayOfMonth() == dayOfMonth) {
                                            endIndex = calculateTimeOfDay(interval.getEnd());
                                            addSpecialDiv(builder, convertToEm(endIndex), EMPTY_UNIT);
                                        }

                                        else if (interval.getStart().getDayOfMonth() == dayOfMonth
                                                && interval.getEnd().getDayOfMonth() == dayOfMonth) {

                                            startIndex = calculateTimeOfDay(interval.getStart());
                                            endIndex = calculateTimeOfDay(interval.getEnd());

                                            if (startIndex == endIndex) {
                                                addSpecialDiv(builder, convertToEm(1),
                                                        convertToEm(startIndex - 1));
                                            } else {
                                                addSpecialDiv(builder, convertToEm((endIndex - startIndex) + 1),
                                                        convertToEm(startIndex - 1));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if (!isEventToMarkWeekendsAndHolidays) {
                    builder.append("</div></td>");
                } else if (!specialDiv) {
                    builder.append("<td class=\"tdnomark\">");
                    if (dayOfMonth <= yearMonthDay.plusMonths(1).minusDays(1).getDayOfMonth()) {
                        LocalDate localDate = yearMonthDay.withDayOfMonth(dayOfMonth).toLocalDate();
                        if (Holiday.isHoliday(localDate)) {
                            builder.append(F);
                        } else if (localDate.getDayOfWeek() == SATURDAY_IN_JODA_TIME) {
                            builder.append("S");
                        } else if (localDate.getDayOfWeek() == SUNDAY_IN_JODA_TIME) {
                            builder.append("D");
                        }
                    }
                    builder.append("</td>");
                }
            }
            if (isShowPeriod()) {
                builder.append("<td class=\"padded smalltxt\" title=\"")
                        .append(event.getGanttDiagramEventPeriod())
                        .append("\"><div style=\"overflow:hidden;\" class=\"nowrap\">")
                        .append(event.getGanttDiagramEventPeriod()).append("</div></td>");
            }
            if (isShowObservations()) {
                builder.append("<td class=\"padded smalltxt\">")
                        .append(event.getGanttDiagramEventObservations()).append("</td>");
            }
            builder.append("</tr>");
        }
        insertNextAndBeforeLinks(builder);
        builder.append("</table>");
    }
    return builder;
}

From source file:com.wicht.benchmark.utils.Benchs.java

private double getExactMean(double mean, Prefix prefix) {
    BigDecimal exactMean = BigDecimal.valueOf(mean);

    exactMean = exactMean.scaleByPowerOfTen(-prefix.getExponent());

    return exactMean.doubleValue();
}

From source file:churashima.action.manage.ReportAction.java

@Execute(validator = false)
public String attendancePersonal() {
    String ym = reportForm.ym;/*from www. j  a  v  a  2s.co  m*/

    int year = Integer.parseInt(ym.substring(0, 4));
    int month = Integer.parseInt(ym.substring(4));

    Calendar calFrom = Calendar.getInstance();
    calFrom.set(Calendar.YEAR, year);
    calFrom.set(Calendar.MONTH, month - 1);
    calFrom.set(Calendar.DAY_OF_MONTH, 1);
    Calendar calTo = Calendar.getInstance();
    calTo.set(Calendar.YEAR, year);
    calTo.set(Calendar.MONTH, month);
    calTo.set(Calendar.DAY_OF_MONTH, 1);

    WorkDao workDao = SingletonS2Container.getComponent(WorkDao.class);
    List<ReportDto> reportDtoList = workDao.selectForReportAttendancePersonal(reportForm.kind,
            calFrom.getTime(), calTo.getTime(), reportForm.userId);

    BigDecimal workHourTotalPersonal = BigDecimal.valueOf(0);
    BigDecimal overHourTotalPersonal = BigDecimal.valueOf(0);
    BigDecimal overHourMorningTotalPersonal = BigDecimal.valueOf(0);
    BigDecimal overHourEveningTotalPersonal = BigDecimal.valueOf(0);
    BigDecimal overHourNightTotalPersonal = BigDecimal.valueOf(0);

    for (ReportDto dto : reportDtoList) {
        workHourTotalPersonal = workHourTotalPersonal.add(dto.workHourTotal);
        overHourTotalPersonal = overHourTotalPersonal.add(dto.overHourTotal);
        overHourMorningTotalPersonal = overHourMorningTotalPersonal.add(dto.overHourMorningTotal);
        overHourEveningTotalPersonal = overHourEveningTotalPersonal.add(dto.overHourEveningTotal);
        overHourNightTotalPersonal = overHourNightTotalPersonal.add(dto.overHourNightTotal);
    }

    reportForm.workHourTotalPersonal = workHourTotalPersonal;
    reportForm.overHourTotalPersonal = overHourTotalPersonal;
    reportForm.overHourMorningTotalPersonal = overHourMorningTotalPersonal;
    reportForm.overHourEveningTotalPersonal = overHourEveningTotalPersonal;
    reportForm.overHourNightTotalPersonal = overHourNightTotalPersonal;

    // ?????
    calFrom.add(Calendar.MONTH, -1);
    calTo.add(Calendar.MONTH, -1);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
    int count = workDao.selectForReportExist(reportForm.kind, calFrom.getTime(), calTo.getTime(),
            reportForm.userId);
    if (count > 0) {
        reportForm.ymBefore = sdf.format(calFrom.getTime());
    } else {
        reportForm.ymBefore = null;
    }

    // ????
    calFrom.add(Calendar.MONTH, +2);
    calTo.add(Calendar.MONTH, +2);
    count = workDao.selectForReportExist(reportForm.kind, calFrom.getTime(), calTo.getTime(),
            reportForm.userId);
    if (count > 0) {
        reportForm.ymNext = sdf.format(calFrom.getTime());
    } else {
        reportForm.ymNext = null;
    }

    reportForm.reportDtoList = reportDtoList;

    return "attendancePersonalReport.jsp";
}

From source file:org.tylproject.data.mongo.ModelTests.java

@Test
public void testUnits() {
    Unit meter = unitRep.findByCode("m");
    assertTrue("Unit with Code=m is not meter but: " + mlTextHelper(meter.getName()).getCurrentText(),
            mlTextHelper(meter.getName()).getCurrentText().equals("meter"));
    SystemOfUnits su = meter.getSystemOfUnits();
    assertTrue("SystemOfUnits of m is not SI but: " + su.getCode(), su.getCode().equals("SI"));
    Unit kilometer = unitRep.findByCode("km");

    Quantity quantityToConvert = new Quantity(BigDecimal.valueOf(10), kilometer.getCode());
    ConversionFactor fromKmToMeter = convFactRep.findByFromAndTo(kilometer, meter);
    Assert.assertEquals(fromKmToMeter.convert(quantityToConvert),
            new Quantity(BigDecimal.valueOf(10000), meter.getCode()));

    quantityToConvert = new Quantity(BigDecimal.valueOf(20000), meter.getCode());
    Assert.assertEquals(fromKmToMeter.reverseConvert(quantityToConvert),
            new Quantity(BigDecimal.valueOf(20), kilometer.getCode()));

}

From source file:com.norconex.importer.handler.tagger.impl.TextStatisticsTagger.java

private String divide(long value, long divisor) {
    return BigDecimal.valueOf(value).divide(BigDecimal.valueOf(divisor), 1, BigDecimal.ROUND_HALF_UP)
            .toString();/*from  w  w w  . java 2 s  .  com*/
}

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

@Test
public void testFindDiscountValuesRuleWinsAgainstPlan() throws CalculationException {
    given(bundleRuleService.getChangePriceBundleRuleForOrderEntry(masterEntry)).willReturn(priceRule);
    given(priceRule.getPrice()).willReturn(BigDecimal.valueOf(RULE_LOW_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("", "priceRule", discount.getCode());
    assertEquals(LAST_RECURRING_PRICE.doubleValue() - RULE_LOW_PRICE.doubleValue(), discount.getValue(), 0.005);
}