List of usage examples for java.math BigDecimal add
public BigDecimal add(BigDecimal augend)
From source file:com.dp2345.entity.Cart.java
/** * ??//from w w w . jav a 2 s.c o m * * @param promotion * * @return ? */ @Transient private BigDecimal getTempPrice(Promotion promotion) { BigDecimal tempPrice = new BigDecimal(0); for (CartItem cartItem : getCartItems(promotion)) { if (cartItem != null && cartItem.getTempPrice() != null) { tempPrice = tempPrice.add(cartItem.getTempPrice()); } } return tempPrice; }
From source file:com.rcv.ResultsWriter.java
private void generateSummarySpreadsheet(Map<Integer, Map<String, BigDecimal>> roundTallies, String precinct, String outputPath) throws IOException { String csvPath = outputPath + ".csv"; Logger.log(Level.INFO, "Generating summary spreadsheets: %s...", csvPath); // Get all candidates sorted by their first round tally. This determines the display order. // container for firstRoundTally Map<String, BigDecimal> firstRoundTally = roundTallies.get(1); // candidates sorted by first round tally List<String> sortedCandidates = sortCandidatesByTally(firstRoundTally); // totalActiveVotesPerRound is a map of round to total votes cast in each round Map<Integer, BigDecimal> totalActiveVotesPerRound = new HashMap<>(); // round indexes over all rounds plus final results round for (int round = 1; round <= numRounds; round++) { // tally is map of candidate to tally for the current round Map<String, BigDecimal> tallies = roundTallies.get(round); // total will contain total votes for all candidates in this round // this is used for calculating other derived data BigDecimal total = BigDecimal.ZERO; // tally indexes over all tallies for the current round for (BigDecimal tally : tallies.values()) { total = total.add(tally); }/*from w w w . ja va 2 s. c om*/ totalActiveVotesPerRound.put(round, total); } // csvPrinter will be used to write output to csv file CSVPrinter csvPrinter; try { BufferedWriter writer = Files.newBufferedWriter(Paths.get(csvPath)); csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT); } catch (IOException exception) { Logger.log(Level.SEVERE, "Error creating CSV file: %s\n%s", csvPath, exception.toString()); throw exception; } // print contest info addHeaderRows(csvPrinter, precinct); // add a row header for the round column labels csvPrinter.print("Rounds"); // round indexes over all rounds for (int round = 1; round <= numRounds; round++) { // label string will have the actual text which goes in the cell String label = String.format("Round %d", round); // cell for round label csvPrinter.print(label); } csvPrinter.println(); // actions don't make sense in individual precinct results if (precinct == null || precinct.isEmpty()) { addActionRows(csvPrinter); } final BigDecimal totalActiveVotesFirstRound = totalActiveVotesPerRound.get(1); // For each candidate: for each round: output total votes // candidate indexes over all candidates for (String candidate : sortedCandidates) { // show each candidate row with their totals for each round // text for the candidate name String candidateDisplayName = this.config.getNameForCandidateID(candidate); csvPrinter.print(candidateDisplayName); // round indexes over all rounds for (int round = 1; round <= numRounds; round++) { // vote tally this round BigDecimal thisRoundTally = roundTallies.get(round).get(candidate); // not all candidates may have a tally in every round if (thisRoundTally == null) { thisRoundTally = BigDecimal.ZERO; } // total votes cell csvPrinter.print(thisRoundTally.toString()); } // advance to next line csvPrinter.println(); } // row for the inactive CVR counts // inactive CVR header cell csvPrinter.print("Inactive ballots"); // round indexes through all rounds for (int round = 1; round <= numRounds; round++) { // count of votes inactive this round BigDecimal thisRoundInactive = BigDecimal.ZERO; if (round > 1) { // Exhausted count is the difference between the total votes in round 1 and the total votes // in the current round. thisRoundInactive = totalActiveVotesFirstRound.subtract(totalActiveVotesPerRound.get(round)) .subtract(roundToResidualSurplus.get(round)); } // total votes cell csvPrinter.print(thisRoundInactive.toString()); } csvPrinter.println(); // row for residual surplus (if needed) // We check if we accumulated any residual surplus over the course of the tabulation by testing // whether the value in the final round is positive. if (roundToResidualSurplus.get(numRounds).signum() == 1) { csvPrinter.print("Residual surplus"); for (int round = 1; round <= numRounds; round++) { csvPrinter.print(roundToResidualSurplus.get(round).toString()); } csvPrinter.println(); } // write xls to disk try { // output stream is used to write data to disk csvPrinter.flush(); csvPrinter.close(); } catch (IOException exception) { Logger.log(Level.SEVERE, "Error saving file: %s\n%s", outputPath, exception.toString()); throw exception; } }
From source file:de.hybris.platform.commercefacades.order.impl.DefaultCartFacade.java
@Override public CartData estimateExternalTaxes(final String deliveryZipCode, final String countryIsoCode) { final CartModel currentCart = getCartService().getSessionCart(); final CommerceCartParameter parameter = new CommerceCartParameter(); parameter.setEnableHooks(true);/*w ww . j a v a2 s .co m*/ parameter.setCart(currentCart); parameter.setDeliveryZipCode(deliveryZipCode); parameter.setDeliveryCountryIso(countryIsoCode); final BigDecimal taxTotal = commerceCartService.estimateTaxes(parameter).getTax(); final CartData sessionCart = getSessionCart(); final PriceData taxData = priceDataFactory.create(PriceDataType.BUY, taxTotal, currentCart.getCurrency()); final PriceData totalPriceData = priceDataFactory.create(PriceDataType.BUY, taxTotal.add(sessionCart.getTotalPrice().getValue()), currentCart.getCurrency()); sessionCart.setTotalTax(taxData); sessionCart.setTotalPrice(totalPriceData); sessionCart.setNet(false); return sessionCart; }
From source file:com.willetinc.hadoop.mapreduce.dynamodb.BigDecimalSplitter.java
@Override void generateRangeKeySplits(Configuration conf, List<InputSplit> splits, Types hashKeyType, AttributeValue hashKeyValue, Types rangeKeyType, AttributeValue minRangeKeyValue, AttributeValue maxRangeKeyValue, int numRangeSplits) { BigDecimal numSplits = BigDecimal.valueOf(numRangeSplits); BigDecimal minVal = new BigDecimal(minRangeKeyValue.getN()); BigDecimal maxVal = new BigDecimal(maxRangeKeyValue.getN()); // Get all the split points together. List<BigDecimal> splitPoints = split(numSplits, minVal, maxVal); // Turn the split points into a set of intervals. BigDecimal start = splitPoints.get(0); for (int i = 1; i < splitPoints.size(); i++) { BigDecimal end = splitPoints.get(i); List<AttributeValue> rangeKeyValues = new ArrayList<AttributeValue>(); rangeKeyValues.add(new AttributeValue().withN(start.toString())); rangeKeyValues.add(new AttributeValue().withN(end.toString())); splits.add(new DynamoDBQueryInputFormat.DynamoDBQueryInputSplit(hashKeyType, hashKeyValue, rangeKeyType, rangeKeyValues, ComparisonOperator.BETWEEN)); // set start to end of last interval plus minimum positive value // in the case of DynamoDB Numbers it is 1.0^-38: // This is necessary to ensure we don't miss any values between // intervals. start = end.add(MIN_POSITIVE_VALUE); }/*w w w. j av a 2 s . c om*/ }
From source file:com.gst.portfolio.tax.serialization.TaxValidator.java
private void validateGroupTotal(final Set<TaxGroupMappings> taxMappings, final DataValidatorBuilder baseDataValidator, final String paramenter) { for (TaxGroupMappings groupMappingsOne : taxMappings) { Collection<LocalDate> dates = groupMappingsOne.getTaxComponent().allStartDates(); for (LocalDate date : dates) { LocalDate applicableDate = date.plusDays(1); BigDecimal total = BigDecimal.ZERO; for (TaxGroupMappings groupMappings : taxMappings) { if (groupMappings.occursOnDayFromAndUpToAndIncluding(applicableDate)) { BigDecimal applicablePercentage = groupMappings.getTaxComponent() .getApplicablePercentage(applicableDate); if (applicablePercentage != null) { total = total.add(applicablePercentage); }/*from w ww.j a v a2s . c o m*/ } } baseDataValidator.reset().parameter(paramenter).value(total) .notGreaterThanMax(BigDecimal.valueOf(100)); } } }
From source file:net.sourceforge.fenixedu.domain.residence.StudentsPerformanceReport.java
private BigDecimal getEnrolledECTS(final Student student) { StudentCurricularPlan scp = getStudentCurricularPlan(student, getExecutionSemester()); BigDecimal totalECTS = new BigDecimal(0d); for (final CurriculumLine curriculumLine : scp.getAllCurriculumLines()) { if (curriculumLine.isExtraCurricular()) { continue; }//from www . j a v a 2s . co m // until given ExecutionSemester if (curriculumLine.getExecutionPeriod().isAfter(getExecutionSemester())) { continue; } if (curriculumLine.isEnrolment()) { final Enrolment enrolment = (Enrolment) curriculumLine; totalECTS = totalECTS.add(enrolment.getEctsCreditsForCurriculum()); } else if (curriculumLine.isDismissal()) { final Dismissal dismissal = (Dismissal) curriculumLine; if (dismissal.getCredits().isSubstitution()) { for (final IEnrolment enrolment : dismissal.getSourceIEnrolments()) { totalECTS = totalECTS.add(enrolment.getEctsCreditsForCurriculum()); } } else if (dismissal.getCredits().isEquivalence()) { totalECTS = totalECTS.add(dismissal.getEctsCreditsForCurriculum()); } } else { throw new RuntimeException("error.unknown.curriculumLine"); } } return totalECTS; }
From source file:mx.edu.um.mateo.inventario.web.EntradaController.java
@RequestMapping("/ver/{id}") public String ver(@PathVariable Long id, Model modelo) { log.debug("Mostrando entrada {}", id); Entrada entrada = entradaDao.obtiene(id); switch (entrada.getEstatus().getNombre()) { case Constantes.ABIERTA: modelo.addAttribute("puedeEditar", true); modelo.addAttribute("puedeEliminar", true); modelo.addAttribute("puedeCerrar", true); modelo.addAttribute("puedePendiente", true); break;// w ww .j av a 2 s.c o m case Constantes.PENDIENTE: modelo.addAttribute("puedeEditarPendiente", true); break; case Constantes.CERRADA: modelo.addAttribute("puedeCancelar", true); break; } modelo.addAttribute("entrada", entrada); BigDecimal subtotal = new BigDecimal("0").setScale(2, RoundingMode.HALF_UP); BigDecimal iva = new BigDecimal("0").setScale(2, RoundingMode.HALF_UP); for (LoteEntrada lote : entrada.getLotes()) { subtotal = subtotal.add(lote.getPrecioUnitario().multiply(lote.getCantidad())); iva = iva.add(lote.getIva()); } BigDecimal total = subtotal.add(iva); modelo.addAttribute("subtotal", subtotal.setScale(2, RoundingMode.HALF_UP)); modelo.addAttribute("iva", iva); modelo.addAttribute("total", total.setScale(2, RoundingMode.HALF_UP)); if (iva.compareTo(entrada.getIva()) == 0 && total.compareTo(entrada.getTotal()) == 0) { modelo.addAttribute("estiloTotales", "label label-success"); } else { BigDecimal variacion = new BigDecimal("0.05"); BigDecimal topeIva = entrada.getIva().multiply(variacion); BigDecimal topeTotal = entrada.getTotal().multiply(variacion); log.debug("Estilos {} {} {} {} {} {}", new Object[] { iva, entrada.getIva(), topeIva, total, entrada.getTotal(), topeTotal }); if (iva.compareTo(entrada.getIva()) < 0 || total.compareTo(entrada.getTotal()) < 0) { log.debug("La diferencia es menor"); if (iva.compareTo(entrada.getIva().subtract(topeIva)) >= 0 && total.compareTo(entrada.getTotal().subtract(topeTotal)) >= 0) { modelo.addAttribute("estiloTotales", "label label-warning"); } else { modelo.addAttribute("estiloTotales", "label label-important"); } } else { log.debug("La diferencia es mayor {} {}", new Object[] { iva.compareTo(entrada.getIva().add(topeIva)), total.compareTo(entrada.getTotal().add(topeTotal)) }); if (iva.compareTo(entrada.getIva().add(topeIva)) <= 0 && total.compareTo(entrada.getTotal().add(topeTotal)) <= 0) { log.debug("estilo warning"); modelo.addAttribute("estiloTotales", "label label-warning"); } else { log.debug("estilo error"); modelo.addAttribute("estiloTotales", "label label-important"); } } } return "inventario/entrada/ver"; }
From source file:com.dp2345.entity.Cart.java
/** * ??// w ww. j a v a2 s .c o m * * @return ? */ @Transient public BigDecimal getPrice() { BigDecimal price = new BigDecimal(0); if (getCartItems() != null) { for (CartItem cartItem : getCartItems()) { if (cartItem != null && cartItem.getSubtotal() != null) { price = price.add(cartItem.getSubtotal()); } } } return price; }
From source file:com.tasktop.c2c.server.internal.tasks.domain.conversion.TaskConverter.java
@SuppressWarnings("unchecked") @Override/*from w ww . j ava2 s .co m*/ public void copy(Task target, Object internalObject, DomainConverter converter, DomainConversionContext context) { com.tasktop.c2c.server.internal.tasks.domain.Task source = (com.tasktop.c2c.server.internal.tasks.domain.Task) internalObject; DomainConversionContext subcontext = context.subcontext(); target.setId(source.getId()); target.setFoundInRelease( source.getVersion() == null ? null : source.getVersion().isEmpty() ? null : source.getVersion()); target.setCreationDate(source.getCreationTs()); target.setModificationDate(source.getDeltaTs()); target.setVersion(source.getDeltaTs() == null ? null : Long.toString(source.getDeltaTs().getTime())); target.setShortDescription(source.getShortDesc()); target.setEstimatedTime(source.getEstimatedTime()); target.setRemainingTime(source.getRemainingTime()); target.setDeadline(source.getDeadline()); target.setUrl(configuration.getWebUrlForTask(target.getId())); // Mandatory custom fields target.setTaskType(source.getTaskType()); List<ExternalTaskRelation> externalTaskRelations = new ArrayList<ExternalTaskRelation>(); if (source.getExternalTaskRelations() != null) { String[] strings = StringUtils.split(source.getExternalTaskRelations(), "\n"); Pattern p = Pattern.compile("(.*)\\.(.*): (.*)"); for (String string : strings) { Matcher matcher = p.matcher(string); if (matcher.matches()) { String type = matcher.group(1); String kind = matcher.group(2); String uri = matcher.group(3); externalTaskRelations.add(new ExternalTaskRelation(type, kind, uri)); } } } target.setExternalTaskRelations(externalTaskRelations); List<String> commits = new ArrayList<String>(); if (source.getCommits() != null) { for (String commit : StringUtils.split(source.getCommits(), ",")) { commits.add(commit); } } target.setCommits(commits); // These must be set from query join results target.setSeverity(context.getTaskSeverity(source.getSeverity())); target.setStatus(context.getTaskStatus(source.getStatus())); target.setResolution(context.getTaskResolution(source.getResolution())); target.setPriority(context.getPriority(source.getPriority())); target.setMilestone(context.getMilestone(source.getProduct(), source.getTargetMilestone())); target.setProduct((Product) converter.convert(source.getProduct(), subcontext)); target.setComponent((Component) converter.convert(source.getComponent(), subcontext)); target.setReporter((TaskUserProfile) converter.convert(source.getReporter(), subcontext)); target.setAssignee((TaskUserProfile) converter.convert(source.getAssignee(), subcontext)); target.setWatchers((List<TaskUserProfile>) converter.convert(source.getCcs(), subcontext)); List<Keyworddef> keyworddefs = new ArrayList<Keyworddef>(); for (com.tasktop.c2c.server.internal.tasks.domain.Keyword keyword : source.getKeywordses()) { keyworddefs.add(keyword.getKeyworddefs()); } target.setKeywords((List<Keyword>) converter.convert(keyworddefs, subcontext)); // Description (first comment), Comments, and Worklog items (comment with workTime) copyCommentsAndWorkLogs(target, source.getComments(), converter, context); BigDecimal sumOfSubtasksEstimate = BigDecimal.ZERO; BigDecimal sumOfSubtasksTimeSpent = BigDecimal.ZERO; Queue<Dependency> subTaskQueue = new LinkedList<Dependency>(source.getDependenciesesForBlocked()); while (!subTaskQueue.isEmpty()) { com.tasktop.c2c.server.internal.tasks.domain.Task subTask = subTaskQueue.poll().getBugsByDependson(); subTaskQueue.addAll(subTask.getDependenciesesForBlocked()); if (subTask.getEstimatedTime() != null) { sumOfSubtasksEstimate = sumOfSubtasksEstimate.add(subTask.getEstimatedTime()); } for (com.tasktop.c2c.server.internal.tasks.domain.Comment c : subTask.getComments()) { if (c.getWorkTime() != null && c.getWorkTime().signum() > 0) { sumOfSubtasksTimeSpent = sumOfSubtasksTimeSpent.add(c.getWorkTime()); } } } target.setSumOfSubtasksEstimatedTime(sumOfSubtasksEstimate); target.setSumOfSubtasksTimeSpent(sumOfSubtasksTimeSpent); if (!context.isThin()) { target.setBlocksTasks(new ArrayList<Task>(source.getDependenciesesForDependson().size())); for (Dependency dep : source.getDependenciesesForDependson()) { target.getBlocksTasks().add(shallowCopyAssociate(dep.getBugsByBlocked(), subcontext)); } target.setSubTasks(new ArrayList<Task>(source.getDependenciesesForBlocked().size())); for (Dependency dep : source.getDependenciesesForBlocked()) { target.getSubTasks().add(shallowCopyAssociate(dep.getBugsByDependson(), subcontext)); } if (source.getDuplicatesByBugId() != null) { target.setDuplicateOf( shallowCopyAssociate(source.getDuplicatesByBugId().getBugsByDupeOf(), subcontext)); } target.setDuplicates(new ArrayList<Task>()); for (Duplicate duplicate : source.getDuplicatesesForDupeOf()) { target.getDuplicates().add(shallowCopyAssociate(duplicate.getBugsByBugId(), subcontext)); } if (source.getStatusWhiteboard() != null && !source.getStatusWhiteboard().isEmpty()) { // A non-empty statusWhiteboard means we store description there for backward compatibility. (See // discussion in Task 422) target.setDescription(source.getStatusWhiteboard()); // REVIEW do we really need this for subtasks? target.setWikiRenderedDescription( renderer.render(source.getStatusWhiteboard(), context.getWikiMarkup())); } target.setAttachments((List<Attachment>) converter.convert(source.getAttachments(), subcontext)); } else { // THIN tasks still get their parent populated if (!source.getDependenciesesForDependson().isEmpty()) { target.setParentTask(shallowCopyAssociate( source.getDependenciesesForDependson().get(0).getBugsByBlocked(), subcontext)); } } }
From source file:com.roncoo.pay.app.reconciliation.biz.ReconciliationCheckBiz.java
/** * ??/*from ww w.ja v a2s . c om*/ * * @param platformDateList * ?dilldate?? * @param bankList * ??? * * @param misTakeList * list * @param screatchRecordList * ??list * * @param batch * */ private void baseOnPaltForm(List<RpTradePaymentRecord> platformDateList, List<ReconciliationEntityVo> bankList, List<RpAccountCheckMistake> misTakeList, List<RpAccountCheckMistakeScratchPool> screatchRecordList, RpAccountCheckBatch batch) { BigDecimal platTradeAmount = BigDecimal.ZERO;// ?? BigDecimal platFee = BigDecimal.ZERO;// ? Integer tradeCount = 0;// ?? Integer mistakeCount = 0; for (RpTradePaymentRecord record : platformDateList) { Boolean flag = false;// ?? // ?? platTradeAmount = platTradeAmount.add(record.getOrderAmount()); platFee = platFee.add(record.getPlatCost() == null ? BigDecimal.ZERO : record.getPlatCost()); tradeCount++; for (ReconciliationEntityVo bankRecord : bankList) { // ???? if (record.getBankOrderNo().equalsIgnoreCase(bankRecord.getBankOrderNo())) { flag = true;// ?? /** step1:??? **/ // ?? if (record.getOrderAmount().compareTo(bankRecord.getBankAmount()) == 1) { // ??? RpAccountCheckMistake misktake = createMisktake(null, record, bankRecord, ReconciliationMistakeTypeEnum.PLATFORM_OVER_CASH_MISMATCH, batch); misTakeList.add(misktake); mistakeCount++; break; } // ?? else if (record.getOrderAmount().compareTo(bankRecord.getBankAmount()) == -1) { // ??? RpAccountCheckMistake misktake = createMisktake(null, record, bankRecord, ReconciliationMistakeTypeEnum.PLATFORM_SHORT_CASH_MISMATCH, batch); misTakeList.add(misktake); mistakeCount++; break; } /** step2:?? **/ if (record.getPlatCost().compareTo(bankRecord.getBankFee()) != 0) { // ??? RpAccountCheckMistake misktake = createMisktake(null, record, bankRecord, ReconciliationMistakeTypeEnum.FEE_MISMATCH, batch); misTakeList.add(misktake); mistakeCount++; break; } } } // ?? if (!flag) { RpAccountCheckMistakeScratchPool screatchRecord = getScratchRecord(record, batch); screatchRecordList.add(screatchRecord); } } // ?? batch.setTradeAmount(platTradeAmount); batch.setTradeCount(tradeCount); batch.setFee(platFee); batch.setMistakeCount(mistakeCount); }