Example usage for java.math BigDecimal ZERO

List of usage examples for java.math BigDecimal ZERO

Introduction

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

Prototype

BigDecimal ZERO

To view the source code for java.math BigDecimal ZERO.

Click Source Link

Document

The value 0, with a scale of 0.

Usage

From source file:client.Pi.java

/**
 * Compute the value, in radians, of the arctangent of 
 * the inverse of the supplied integer to the specified
 * number of digits after the decimal point.  The value
 * is computed using the power series expansion for the
 * arc tangent://from  w ww .  j av  a  2 s  . co  m
 *
 * arctan(x) = x - (x^3)/3 + (x^5)/5 - (x^7)/7 + 
 *     (x^9)/9 ...
 */
public static BigDecimal arctan(int inverseX, int scale) {
    BigDecimal result, numer, term;
    BigDecimal invX = BigDecimal.valueOf(inverseX);
    BigDecimal invX2 = BigDecimal.valueOf(inverseX * inverseX);

    numer = BigDecimal.ONE.divide(invX, scale, roundingMode);

    result = numer;
    int i = 1;
    do {
        numer = numer.divide(invX2, scale, roundingMode);
        int denom = 2 * i + 1;
        term = numer.divide(BigDecimal.valueOf(denom), scale, roundingMode);
        if ((i % 2) != 0) {
            result = result.subtract(term);
        } else {
            result = result.add(term);
        }
        i++;
    } while (term.compareTo(BigDecimal.ZERO) != 0);
    return result;
}

From source file:id.ac.ipb.ilkom.training.controller.OrderController.java

@RequestMapping(value = "/add-to-cart", method = RequestMethod.POST)
@ResponseBody// w w  w  .  ja  v  a2  s.  c  o m
public AddToCartResponse addToCart(Integer productId, Integer quantity, HttpSession session) {
    //check if user already login or not
    Customer customer = (Customer) session.getAttribute("customer");
    if (customer == null) {
        AddToCartResponse response = new AddToCartResponse();
        response.setResult(false);
        response.setErrorMessage("Please login before buy product.");
        return response;
    }
    //check product
    Product product = productService.getProduct(productId);
    if (product == null) {
        AddToCartResponse response = new AddToCartResponse();
        response.setResult(false);
        response.setErrorMessage("Product id " + productId + " is not found .");
        return response;
    }
    Order order = (Order) session.getAttribute("cart");
    if (order == null) {
        List<OrderItem> orderItems = new ArrayList<>();
        order = new Order();
        order.setOrderItems(orderItems);
    }
    boolean isProductFoundInOrderItems = false;
    for (OrderItem orderItem : order.getOrderItems()) {
        if (orderItem.getProduct().getId().equals(productId)) {
            orderItem.setQuantity(orderItem.getQuantity() + quantity);
            isProductFoundInOrderItems = true;
            break;
        }
    }
    if (!isProductFoundInOrderItems) {
        OrderItem orderItem = new OrderItem();
        orderItem.setQuantity(quantity);
        orderItem.setProduct(product);
        orderItem.setPrice(product.getPrice());
        orderItem.setOrder(order); //tambahan
        order.getOrderItems().add(orderItem);
    }
    BigDecimal total = BigDecimal.ZERO;
    for (OrderItem orderItem : order.getOrderItems()) {
        BigDecimal price = orderItem.getPrice();
        BigDecimal subTotal = price.multiply(new BigDecimal(orderItem.getQuantity()));
        total = total.add(subTotal);
    }
    order.setCreatedDate(new Date());
    order.setCustomer(customer);
    order.setTotal(total);
    //check
    session.setAttribute("cart", order);
    AddToCartResponse response = new AddToCartResponse();
    response.setResult(true);
    return response;
}

From source file:mx.edu.um.mateo.rh.dao.EmpleadoDaoTest.java

/**
 * Test of lista method, of class EmpleadoDao.
 *//*from  w ww  .j  a  v a2  s  .  c o m*/
@SuppressWarnings("unchecked")
@Test
public void debieraMostrarListaDeEmpleados() {
    log.debug("Debiera mostrar lista de empleados");
    Organizacion organizacion = new Organizacion("tst-01", "test-01", "test-01");
    currentSession().save(organizacion);
    Empresa empresa = new Empresa("tst-01", "test-01", "test-01", "000000000001", organizacion);
    currentSession().save(empresa);
    for (int i = 0; i < 20; i++) {
        Empleado empleado = new Empleado("test0" + (i + 10), "test", "test", "test", "M", "address", "A",
                "curp", "rfc", "cuenta", "imss", 10, 100, BigDecimal.ZERO, "mo", "ife", "ra", Boolean.TRUE,
                "padre", "madre", "C", "Conyugue", Boolean.TRUE, Boolean.TRUE, "iglesia", "responsabilidad",
                empresa);
        instance.graba(empleado);
    }
    Map<String, Object> params = new HashMap<>();
    params.put("empresa", empresa.getId());
    Map<String, Object> result = instance.lista(params);
    assertNotNull(result.get(Constants.EMPLEADO_LIST));
    assertNotNull(result.get("cantidad"));
    assertEquals(10, ((List<Empleado>) result.get(Constants.EMPLEADO_LIST)).size());
    assertEquals(20, ((Long) result.get("cantidad")).intValue());
}

From source file:net.sourceforge.fenixedu.domain.credits.util.DepartmentCreditsPoolBean.java

protected void setValues() {
    departmentSharedExecutionCourses = new TreeSet<DepartmentExecutionCourse>();
    departmentExecutionCourses = new TreeSet<DepartmentExecutionCourse>();
    otherDepartmentSharedExecutionCourses = new TreeSet<DepartmentExecutionCourse>();
    availableCredits = BigDecimal.ZERO;
    assignedCredits = BigDecimal.ZERO;
    if (departmentCreditsPool != null) {
        for (ExecutionSemester executionSemester : getAnnualCreditsState().getExecutionYear()
                .getExecutionPeriodsSet()) {
            for (ExecutionCourse executionCourse : executionSemester.getAssociatedExecutionCoursesSet()) {
                if (!(executionCourse.isDissertation() || executionCourse.getProjectTutorialCourse())) {
                    if (executionCourse.getDepartments().contains(getDepartment())) {
                        if (isSharedExecutionCourse(executionCourse)) {
                            addToSet(departmentSharedExecutionCourses, executionCourse);
                        } else {
                            addToSet(departmentExecutionCourses, executionCourse);
                        }// ww w  .ja  va  2 s . c  om
                    } else if (isTaughtByTeacherFromThisDepartment(executionCourse)) {
                        addToSet(otherDepartmentSharedExecutionCourses, executionCourse);
                    }
                }
            }
        }
        assignedCredits = assignedCredits.setScale(2, BigDecimal.ROUND_HALF_UP);
        availableCredits = departmentCreditsPool.getCreditsPool().subtract(assignedCredits).setScale(2,
                BigDecimal.ROUND_HALF_UP);
    }
}

From source file:org.openmrs.module.openhmis.cashier.api.impl.BillServiceImpl.java

/**
 * Saves the bill to the database, creating a new bill or updating an existing one.
 * @param bill The bill to be saved./*ww  w. j av a2 s. c  o m*/
 * @return The saved bill.
 * @should Generate a new receipt number if one has not been defined.
 * @should Not generate a receipt number if one has already been defined.
 * @should Throw APIException if receipt number cannot be generated.
 */
@Override
@Authorized({ PrivilegeConstants.MANAGE_BILLS })
@Transactional
public Bill save(Bill bill) {
    if (bill == null) {
        throw new NullPointerException("The bill must be defined.");
    }

    /* Check for refund.
     * A refund is given when the total of the bill's line items is negative.
     */
    if (bill.getTotal().compareTo(BigDecimal.ZERO) < 0
            && !Context.hasPrivilege(PrivilegeConstants.REFUND_MONEY)) {
        throw new AccessControlException("Access denied to give a refund.");
    }
    IReceiptNumberGenerator generator = ReceiptNumberGeneratorFactory.getGenerator();
    if (generator == null) {
        LOG.warn(
                "No receipt number generator has been defined.  Bills will not be given a receipt number until one is"
                        + " defined.");
    } else {
        if (StringUtils.isEmpty(bill.getReceiptNumber())) {
            bill.setReceiptNumber(generator.generateNumber(bill));
        }
    }

    return super.save(bill);
}

From source file:org.homiefund.api.service.impl.DebtPreviewServiceImpl.java

@Override
@Transactional(readOnly = true)/*from w ww .  j av a  2 s.  co m*/
public DebtPreviewDTO getOverview() {
    Graph debtGraph = new Graph();

    Collection<DebtPreview> list = debtPreviewDAO
            .getTransactionsForPreview(mapper.map(userPreferencesBean.getPreferredHome(), Home.class));
    int i = 0;
    for (DebtPreview p : list) {
        i++;
        debtGraph.add(p);
    }

    Long principalID = securityService.getPrincipal().getId();
    Map<Long, BigDecimal> debtMap = debtGraph.debts(principalID);

    Map<UserDTO, BigDecimal> debtsMap = debtMap.entrySet().stream().filter(d -> !d.getKey().equals(principalID))
            .sorted(comparingByValue((o1, o2) -> o2.compareTo(o1)))
            .collect(Collectors.toMap(e -> mapper.map(userDAO.getById(e.getKey()), UserDTO.class),
                    e -> e.getValue(), (e1, e2) -> e1, LinkedHashMap::new));

    DebtPreviewDTO debts = new DebtPreviewDTO();
    debts.setOverview(debtsMap);
    debts.setTotal(debtsMap.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add));

    return debts;
}

From source file:org.ng200.openolympus.controller.user.SolutionStatusController.java

@RequestMapping(value = "/solution", method = RequestMethod.GET)
public String viewSolutionStatus(final HttpServletRequest request, final Model model,
        @RequestParam(value = "id") final Solution solution, final Principal principal) {
    if (principal == null || (!solution.getUser().getUsername().equals(principal.getName())
            && !request.isUserInRole(Role.SUPERUSER))) {
        throw new InsufficientAuthenticationException(
                "You attempted to view a solution that doesn't belong to you!");
    }/*from   ww w.j a  v  a  2 s . c  o m*/

    this.assertSuperuserOrTaskAllowed(principal, solution.getTask());
    model.addAttribute("solution", solution);
    final List<Verdict> verdicts = this.solutionService.getVerdicts(solution);
    model.addAttribute("completeScore",
            verdicts.stream().map((x) -> x.getScore()).reduce((x, y) -> x.add(y)).orElse(BigDecimal.ZERO));
    model.addAttribute("completeMaximumScore", verdicts.stream().map((x) -> x.getMaximumScore())
            .reduce((x, y) -> x.add(y)).orElse(BigDecimal.ZERO));
    model.addAttribute("verdicts", verdicts.stream().sorted((l, r) -> Long.compare(l.getId(), r.getId()))
            .collect(Collectors.toList()));
    model.addAttribute("verdictMessageStrings", new HashMap<SolutionResult.Result, String>() {
        /**
         *
         */
        private static final long serialVersionUID = 8526897014680785208L;

        {
            this.put(SolutionResult.Result.OK, "solution.result.ok");
            this.put(SolutionResult.Result.TIME_LIMIT, "solution.result.timeLimit");
            this.put(SolutionResult.Result.MEMORY_LIMIT, "solution.result.memoryLimit");
            this.put(SolutionResult.Result.OUTPUT_LIMIT, "solution.result.outputLimit");
            this.put(SolutionResult.Result.RUNTIME_ERROR, "solution.result.runtimeError");
            this.put(SolutionResult.Result.INTERNAL_ERROR, "solution.result.internalError");
            this.put(SolutionResult.Result.SECURITY_VIOLATION, "solution.result.securityViolation");
            this.put(SolutionResult.Result.COMPILE_ERROR, "solution.result.compileError");
            this.put(SolutionResult.Result.PRESENTATION_ERROR, "solution.result.presentationError");
            this.put(SolutionResult.Result.WRONG_ANSWER, "solution.result.wrongAnswer");

        }
    });

    return "tasks/solution";
}

From source file:com.haulmont.timesheets.gui.approve.BulkTimeEntriesApprove.java

@Override
public void init(Map<String, Object> params) {
    super.init(params);

    if (securityAssistant.isSuperUser()) {
        timeEntriesDs.setQuery("select e from ts$TimeEntry e "
                + "where e.date >= :component$dateFrom and e.date <= :component$dateTo");
    }//from w ww. j a va 2 s. c o m

    timeEntriesTable.getColumn("overtime")
            .setAggregation(ComponentsHelper.createAggregationInfo(
                    projectsService.getEntityMetaPropertyPath(TimeEntry.class, "overtime"),
                    new TimeEntryOvertimeAggregation()));

    timeEntriesDs.addCollectionChangeListener(e -> {
        Multimap<Map<String, Object>, TimeEntry> map = ArrayListMultimap.create();
        for (TimeEntry item : timeEntriesDs.getItems()) {
            Map<String, Object> key = new TreeMap<>();
            key.put("user", item.getUser());
            key.put("date", item.getDate());
            map.put(key, item);
        }

        for (Map.Entry<Map<String, Object>, Collection<TimeEntry>> entry : map.asMap().entrySet()) {
            BigDecimal thisDaysSummary = BigDecimal.ZERO;
            for (TimeEntry timeEntry : entry.getValue()) {
                thisDaysSummary = thisDaysSummary.add(timeEntry.getTimeInHours());
            }

            for (TimeEntry timeEntry : entry.getValue()) {
                BigDecimal planHoursForDay = workdaysTools.isWorkday(timeEntry.getDate())
                        ? workTimeConfigBean.getWorkHourForDay()
                        : BigDecimal.ZERO;
                BigDecimal overtime = thisDaysSummary.subtract(planHoursForDay);
                timeEntry.setOvertimeInHours(overtime);
            }
        }
    });

    Date previousMonth = DateUtils.addMonths(timeSource.currentTimestamp(), -1);
    dateFrom.setValue(DateUtils.truncate(previousMonth, Calendar.MONTH));
    dateTo.setValue(DateUtils.addDays(DateUtils.truncate(timeSource.currentTimestamp(), Calendar.MONTH), -1));

    approve.addAction(new AbstractAction("approveAll") {
        @Override
        public void actionPerform(Component component) {
            setStatus(timeEntriesDs.getItems(), TimeEntryStatus.APPROVED);
        }
    });

    approve.addAction(new AbstractAction("approveSelected") {
        @Override
        public void actionPerform(Component component) {
            setStatus(timeEntriesTable.getSelected(), TimeEntryStatus.APPROVED);
        }
    });

    reject.addAction(new AbstractAction("rejectAll") {
        @Override
        public void actionPerform(Component component) {
            setStatus(timeEntriesDs.getItems(), TimeEntryStatus.REJECTED);
        }
    });

    reject.addAction(new AbstractAction("rejectSelected") {
        @Override
        public void actionPerform(Component component) {
            setStatus(timeEntriesTable.getSelected(), TimeEntryStatus.REJECTED);
        }
    });

    status.setOptionsList(Arrays.asList(TimeEntryStatus.values()));
    user.setOptionsList(
            projectsService.getManagedUsers(userSession.getCurrentOrSubstitutedUser(), View.MINIMAL));
}

From source file:uk.dsxt.voting.client.ClientManager.java

public RequestResult getVotings(String clientId) {
    final Collection<Voting> votings = assetsHolder.getVotings().stream()
            .filter(v -> assetsHolder.getClientPacketSize(v.getId(), clientId) == null
                    || assetsHolder.getClientPacketSize(v.getId(), clientId).compareTo(BigDecimal.ZERO) > 0)
            .collect(Collectors.toSet());
    return new RequestResult<>(
            votings.stream().map(v -> new VotingWeb(v, assetsHolder.getClientVote(v.getId(), clientId) == null))
                    .collect(Collectors.toList()).toArray(new VotingWeb[votings.size()]),
            null);//from  w  w  w  .ja v  a 2s  . c  o m
}

From source file:cz.muni.fi.dndtroops.test.HeroDaoImplTest.java

@Test
public void testDeleteHero() throws ConnectionException {
    Hero heroD = new Hero();
    heroD.setName("Hero");
    heroD.setLevel(1);//from  www .j a v a 2 s .  co  m
    heroD.setRole(RoleName.BARD);
    Troop troopD = new Troop();
    troopD.setName("Angels");
    troopD.setMoney(BigDecimal.ZERO);
    troopD.setMission("mise A");
    heroD.setTroop(troopD);

    troopDao.createTroop(troopD);
    heroDao.createHero(heroD);

    heroDao.deleteById(heroD.getId());

    Hero h2 = heroDao.findById(heroD.getId());
    Assert.assertEquals(h2, null);

    Hero heroE = new Hero();
    heroE.setName("Nick");
    heroE.setLevel(1);
    heroE.setRole(RoleName.FIGHTER);
    heroE.setTroop(troopD);

    heroDao.createHero(heroE);

    Hero h3 = heroDao.findById(heroE.getId());
    heroDao.deleteHero(h3);

    Hero h4 = heroDao.findById(heroE.getId());
    Assert.assertEquals(h4, null);

}