List of usage examples for java.math BigDecimal ROUND_HALF_UP
int ROUND_HALF_UP
To view the source code for java.math BigDecimal ROUND_HALF_UP.
Click Source Link
From source file:com.esd.ps.LoginController.java
/** * ,?,?,?//from ww w. j av a2s . c o m * @return */ @RequestMapping(value = "/datas", method = RequestMethod.POST) @ResponseBody public Map<String, Object> datasPost() { Map<String, Object> map = new HashMap<String, Object>(); int peopleCountTotle = workerService.getWorkerCount(); double moneyTotle = 0.00; try { moneyTotle = salaryService.getMoneyTotle(0); } catch (NullPointerException n) { } int taskCountTotle = taskService.getWorkerIdZeroCountByPackId(0); int taskCount = taskService.getCountTaskDoing(1); double moneyToday = 0.00; try { moneyToday = salaryService.getMoneyTotle(1); } catch (NullPointerException n) { moneyToday = 0.00; } BigDecimal b = new BigDecimal(moneyTotle / 18); moneyTotle = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); BigDecimal b1 = new BigDecimal(moneyToday / 18); moneyToday = b1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); map.put("peopleCountTotle", peopleCountTotle); map.put("moneyTotle", moneyTotle); map.put("taskCountTotle", taskCountTotle); map.put("taskCount", taskCount); map.put("moneyToday", moneyToday); return map; }
From source file:com.panet.imeta.core.row.ValueDataUtil.java
/** * 100 * A / B//w ww .j a va2 s. c o m * * @param metaA * @param dataA * @param metaB * @param dataB * @return * @throws KettleValueException */ public static Object percent1(ValueMetaInterface metaA, Object dataA, ValueMetaInterface metaB, Object dataB) throws KettleValueException { if (dataA == null || dataB == null) return null; switch (metaA.getType()) { case ValueMetaInterface.TYPE_NUMBER: return new Double(100.0 * metaA.getNumber(dataA).doubleValue() / metaB.getNumber(dataB).doubleValue()); case ValueMetaInterface.TYPE_INTEGER: return new Long(100 * metaA.getInteger(dataA).longValue() / metaB.getInteger(dataB).longValue()); case ValueMetaInterface.TYPE_BIGNUMBER: return metaA.getBigNumber(dataA).multiply(new BigDecimal(100)).divide(metaB.getBigNumber(dataB), BigDecimal.ROUND_HALF_UP); default: throw new KettleValueException("The 'percent1' function only works on numeric data"); } }
From source file:org.gradoop.flink.datagen.transactions.foodbroker.config.FoodBrokerConfig.java
/** * Adds positive or negative influence to the start value, depending on the * quality of the master data objects.// ww w.ja v a2 s .c o m * * @param influencingMasterDataQuality list of influencing master data quality * @param higherIsBetter true if positiv influence shall be added, negative * influence otherwise * @param influence influence value to be added to the start value * @param startValue the start value * @return aggregated start value */ protected Float getValue(List<Float> influencingMasterDataQuality, boolean higherIsBetter, Float influence, Float startValue) { Float value = startValue; BigDecimal influenceCount = BigDecimal.ZERO; for (float quality : influencingMasterDataQuality) { // check quality value of the masterdata and adjust the result value influenceCount = influenceCount.add(BigDecimal.valueOf(quality)); } if (influenceCount.compareTo(BigDecimal.ZERO) > 0) { influenceCount = influenceCount.setScale(2, BigDecimal.ROUND_HALF_UP); // normalize the quality value influenceCount = influenceCount.divide(BigDecimal.valueOf(influencingMasterDataQuality.size()), 8, RoundingMode.HALF_UP); // subtract the avg normal, for standard config it is 0.5 influenceCount = influenceCount.subtract(getAvgNormal()); // if the normalized value is greater than the avg if (influenceCount.compareTo(BigDecimal.ZERO) == 1) { // calculate how much times the value is greater than the difference // between the avg normal value and the lowest good value influenceCount = influenceCount.divide( BigDecimal.valueOf(getQualityGood()).subtract(getAvgNormal()).abs(), 0, BigDecimal.ROUND_HALF_UP); // if the normalized value is LOWER than the avg } else if (influenceCount.compareTo(BigDecimal.ZERO) == -1) { // calculate how much times the value is smaller than the difference // between the avg normal value and the lowest normal value influenceCount = influenceCount.divide( BigDecimal.valueOf(getQualityNormal()).subtract(getAvgNormal()).abs(), 0, BigDecimal.ROUND_HALF_UP); } } influence *= influenceCount.intValue(); if (higherIsBetter) { value += influence; } else { value -= influence; } return value; }
From source file:org.egov.ptis.web.controller.reports.BaseRegisterResultAdaptor.java
private Map<String, String> getFloorDetails(final PropertyMVInfo propMatView) { final List<FloorDetailsInfo> floorDetailsList = new LinkedList<>(propMatView.getFloorDetails()); final Map<String, String> floorValues = new LinkedHashMap<>(); if (floorDetailsList.size() > 1) { int count = 0; for (final FloorDetailsInfo floorDetailsObj : floorDetailsList) if (count == 0) { floorValues.put(PROPERTY_USAGE, floorDetailsObj.getPropertyUsage()); floorValues.put(CLASSIFICATION, floorDetailsObj.getClassification()); floorValues.put("area", floorDetailsObj.getBuiltUpArea().setScale(2, BigDecimal.ROUND_HALF_UP).toString()); count++;/*from w w w. j a va2 s .co m*/ } else { floorValues.put(PROPERTY_USAGE, floorDetailsObj.getPropertyUsage()); floorValues.put(CLASSIFICATION, floorDetailsObj.getClassification()); floorValues.put("area", floorDetailsObj.getBuiltUpArea().setScale(2, BigDecimal.ROUND_HALF_UP).toString()); } } else for (final FloorDetailsInfo floorDetailsObj : floorDetailsList) { floorValues.put(PROPERTY_USAGE, floorDetailsObj.getPropertyUsage()); floorValues.put(CLASSIFICATION, floorDetailsObj.getClassification()); floorValues.put("area", floorDetailsObj.getBuiltUpArea().setScale(2, BigDecimal.ROUND_HALF_UP).toString()); } return floorValues; }
From source file:net.sourceforge.fenixedu.domain.credits.util.AnnualTeachingCreditsBean.java
public void calculateCredits() { masterDegreeThesesCredits = teacher.getMasterDegreeThesesCredits(executionYear); phdDegreeThesesCredits = teacher.getPhdDegreeThesesCredits(executionYear); projectsTutorialsCredits = teacher.getProjectsTutorialsCredits(executionYear); BigDecimal yearCreditsForFinalCredits = BigDecimal.ZERO; BigDecimal annualTeachingLoadFinalCredits = BigDecimal.ZERO; boolean hasOrientantionCredits = false; boolean hasFinalAndAccumulatedCredits = false; for (ExecutionSemester executionSemester : executionYear.getExecutionPeriodsSet()) { if (getTeacher().isActiveForSemester(executionSemester) || getTeacher().hasTeacherAuthorization(executionSemester)) { BigDecimal thisSemesterManagementFunctionCredits = new BigDecimal( getTeacher().getManagementFunctionsCredits(executionSemester)); managementFunctionCredits = managementFunctionCredits.add(thisSemesterManagementFunctionCredits); serviceExemptionCredits = serviceExemptionCredits .add(new BigDecimal(getTeacher().getServiceExemptionCredits(executionSemester))); BigDecimal thisSemesterTeachingLoad = new BigDecimal( getTeacher().getMandatoryLessonHours(executionSemester)); annualTeachingLoad = annualTeachingLoad.add(thisSemesterTeachingLoad).setScale(2, BigDecimal.ROUND_HALF_UP); TeacherService teacherService = getTeacher().getTeacherServiceByExecutionPeriod(executionSemester); BigDecimal thisSemesterCreditsReduction = BigDecimal.ZERO; if (teacherService != null) { teachingCredits = teachingCredits .add(new BigDecimal(teacherService.getTeachingDegreeCredits())); thisSemesterCreditsReduction = teacherService.getReductionServiceCredits(); othersCredits = othersCredits.add(new BigDecimal(teacherService.getOtherServiceCredits())); }/* w w w . j a va 2 s . co m*/ creditsReduction = creditsReduction.add(thisSemesterCreditsReduction); BigDecimal reductionAndManagement = thisSemesterManagementFunctionCredits .add(thisSemesterCreditsReduction); BigDecimal thisSemesterYearCredits = thisSemesterTeachingLoad; if (thisSemesterTeachingLoad.compareTo(reductionAndManagement) > 0) { thisSemesterYearCredits = reductionAndManagement; } else { setHasAnyLimitation(true); } yearCredits = yearCredits.add(thisSemesterYearCredits); if (getTeacher().isActiveForSemester(executionSemester) && !getTeacher().isMonitor(executionSemester)) { yearCreditsForFinalCredits = yearCreditsForFinalCredits.add(thisSemesterYearCredits); annualTeachingLoadFinalCredits = annualTeachingLoadFinalCredits.add(thisSemesterTeachingLoad); if (executionSemester.getSemester() == 2) { hasFinalAndAccumulatedCredits = true; } else { hasOrientantionCredits = true; } } } } yearCredits = yearCredits.add(teachingCredits).add(serviceExemptionCredits).add(othersCredits); yearCreditsForFinalCredits = yearCreditsForFinalCredits.add(teachingCredits).add(serviceExemptionCredits) .add(othersCredits); if (hasOrientantionCredits) { yearCredits = yearCredits.add(getMasterDegreeThesesCredits()).add(getPhdDegreeThesesCredits()) .add(getProjectsTutorialsCredits()).setScale(2, BigDecimal.ROUND_HALF_UP); yearCreditsForFinalCredits = yearCreditsForFinalCredits.add(getMasterDegreeThesesCredits()) .add(getPhdDegreeThesesCredits()).add(getProjectsTutorialsCredits()); } if (hasFinalAndAccumulatedCredits) { finalCredits = yearCreditsForFinalCredits.subtract(annualTeachingLoadFinalCredits); BigDecimal lastYearAccumulated = getPreviousAccumulatedCredits(); accumulatedCredits = (finalCredits.add(lastYearAccumulated)).setScale(2, BigDecimal.ROUND_HALF_UP); finalCredits = finalCredits.setScale(2, BigDecimal.ROUND_HALF_UP); } }
From source file:org.kalypso.kalypsomodel1d2d.ui.map.flowrel.FlowRelationshipCalcOperation.java
private QIntervallResult runCalculation(final TuhhCalculation templateCalculation, final IFlowRelation1D flowRel, final IProfile[] profiles, final IProgressMonitor monitor) throws InvocationTargetException { File tmpDir = null;//ww w . j av a2 s . c o m try { tmpDir = SimulationUtilitites.createSimulationTmpDir("" + System.currentTimeMillis()); //$NON-NLS-1$ final TuhhCalculation calculation = createCalculation(flowRel, templateCalculation, profiles); // Prepare wspm model final File modelFile = new File(tmpDir, "modell.gml"); //$NON-NLS-1$ final GMLWorkspace calcWorkspace = calculation.getWorkspace(); GmlSerializer.serializeWorkspace(modelFile, calcWorkspace, Charset.defaultCharset().name()); // prepare calcjob final WspmTuhhCalcJob wspmTuhhCalcJob = new WspmTuhhCalcJob(new PrintStream(m_outputStream)); final DefaultSimulationDataProvider inputProvider = new DefaultSimulationDataProvider(); inputProvider.put(WspmTuhhCalcJob.INPUT_MODELL_GML, modelFile.toURI().toURL()); inputProvider.put(WspmTuhhCalcJob.INPUT_CALC_PATH, new GMLXPath(calculation).toString()); // eps-thinning is big, as we do not need the tin result and bigger is faster inputProvider.put(WspmTuhhCalcJob.INPUT_EPS_THINNING, "100.0"); //$NON-NLS-1$ final DefaultSimulationResultEater resultEater = new DefaultSimulationResultEater(); final NullSimulationMonitorExtension simMonitor = new NullSimulationMonitorExtension(monitor); wspmTuhhCalcJob.run(tmpDir, inputProvider, resultEater, simMonitor); if (simMonitor.getFinishStatus() != IStatus.OK) throw new CoreException(new Status(simMonitor.getFinishStatus(), KalypsoModel1D2DPlugin.PLUGIN_ID, simMonitor.getFinishText())); // read simulation log final File logFile = (File) resultEater.getResult(WspmTuhhCalcJob.OUTPUT_SIMULATION_LOG); m_consoleText = FileUtils.readFileToString(logFile, Charset.defaultCharset().name()); // read interval results and remember them final File qintervallFile = (File) resultEater.getResult(WspmTuhhCalcJob.OUTPUT_QINTERVALL_RESULT); final GMLWorkspace qresultsWorkspace = GmlSerializer.createGMLWorkspace(qintervallFile, calcWorkspace.getFeatureProviderFactory()); final QIntervallResultCollection qResultCollection = (QIntervallResultCollection) qresultsWorkspace .getRootFeature(); final IFeatureBindingCollection<QIntervallResult> resultList = qResultCollection.getQIntervalls(); for (final QIntervallResult qresult : resultList) { final BigDecimal flowStation = flowRel.getStation(); if (flowStation == null) { final String message = String.format(Messages.getString("FlowRelationshipCalcOperation.0"), //$NON-NLS-1$ flowRel.getName()); throw new CoreException( new Status(IStatus.ERROR, KalypsoModel1D2DPlugin.PLUGIN_ID, message, null)); //$NON-NLS-1$ } // HACK: we set a scale here in order to get a right comparison with the station value that was read from the // profile. if a rounded station value occurs in the flow relation, the result of the comparison is always // false, because the station value of the flow relation gets rounded and the one of the profile gets not // rounded (read from string with fixed length). // TODO: implement the right setting of the station value for the flow relation with a fixed scale of 4! final BigDecimal station = flowStation.setScale(4, BigDecimal.ROUND_HALF_UP); // FIXME: why do we use the station defined in the relation at all -> the calculation uses the station defined // in the profile anyways // REMARK: sometimes it could be, that the user wants to assign a profile to a new created flow relation. in // this case he is able to to this and to calculate the data, but the assignment will never happen, if the // station is not equal to the station of the assigned profile. if (ObjectUtils.equals(station, qresult.getStation())) return qresult; } final String message = Messages .getString("org.kalypso.kalypsomodel1d2d.ui.map.flowrel.FlowRelationshipCalcOperation.14"); //$NON-NLS-1$ throw new CoreException(new Status(IStatus.ERROR, KalypsoModel1D2DPlugin.PLUGIN_ID, message)); } catch (final InvocationTargetException e) { throw e; } catch (final GMLSchemaException e) { throw new InvocationTargetException(e); } catch (final IOException e) { throw new InvocationTargetException(e); } catch (final GmlSerializeException e) { throw new InvocationTargetException(e); } catch (final SimulationException e) { throw new InvocationTargetException(e); } catch (final GMLXPathException e) { throw new InvocationTargetException(e); } catch (final Exception e) { throw new InvocationTargetException(e); } finally { SimulationUtilitites.clearTmpDir(tmpDir); } }
From source file:org.devgateway.ocds.web.rest.controller.CorruptionRiskDashboardIndicatorsStatsController.java
@ApiOperation(value = "Percent of eligible projects flagged (denominator is number of eligible projects)") @RequestMapping(value = "/api/percentOfEligibleProjectsFlaggedByYear", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json") public List<DBObject> percentOfEligibleProjectsFlaggedByYear(final YearFilterPagingRequest filter) { //get the total projects eligible by year List<DBObject> totalFlaggedProjects = totalFlaggedProjectsByIndicatorTypeByYear(filter); //denominator total projects eligible by year List<DBObject> totalEligibleProjectsByYear = totalEligibleProjectsByIndicatorTypeByYear(filter); //because this is reversed, we may end up with empty percentages on the eligible side, so we need to add zeros totalEligibleProjectsByYear.forEach(e -> { e.put(Keys.PERCENT, BigDecimal.ZERO); e.put(Keys.FLAGGED_PROJECT_COUNT, 0); });// w w w. j a v a 2 s . co m totalEligibleProjectsByYear.forEach(e -> { findByYearAndTypeAndMonth(totalFlaggedProjects, (Integer) e.get(Keys.YEAR), (String) e.get(Keys.TYPE), (Integer) e.get(Keys.MONTH)).forEach(f -> { e.put(Keys.FLAGGED_PROJECT_COUNT, f.get(Keys.FLAGGED_PROJECT_COUNT)); e.put(Keys.PERCENT, (BigDecimal.valueOf((Integer) f.get(Keys.FLAGGED_PROJECT_COUNT)) .setScale(BIGDECIMAL_SCALE) .divide(BigDecimal.valueOf((Integer) e.get(Keys.ELIGIBLE_PROJECT_COUNT)), BigDecimal.ROUND_HALF_UP) .multiply(ONE_HUNDRED))); }); }); return totalEligibleProjectsByYear; }
From source file:es.upm.oeg.tools.quality.ldsniffer.eval.Evaluation.java
private double getPercentage(int count, int total) { //This shouldn't be necessary if (total == 0) { return 0; }/* w w w . j a v a 2s. c o m*/ return new BigDecimal(((double) count / total) * 100).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue(); }
From source file:com.scooter1556.sms.server.service.AdaptiveStreamingService.java
public List<String> generateHLSPlaylist(UUID id, String baseUrl, String type, Integer extra) { // Check variables if (type == null || extra == null) { return null; }/*from w ww . j a v a 2s . co m*/ Job job = jobDao.getJobByID(id); if (job == null) { return null; } MediaElement mediaElement = mediaDao.getMediaElementByID(job.getMediaElement()); if (mediaElement == null) { return null; } List<String> playlist = new ArrayList<>(); playlist.add("#EXTM3U"); playlist.add("#EXT-X-VERSION:4"); playlist.add("#EXT-X-TARGETDURATION:" + String.valueOf(HLS_SEGMENT_DURATION + 1)); playlist.add("#EXT-X-MEDIA-SEQUENCE:0"); playlist.add("#EXT-X-PLAYLIST-TYPE:VOD"); // Get Video Segments for (int i = 0; i < Math.floor(mediaElement.getDuration() / HLS_SEGMENT_DURATION); i++) { playlist.add("#EXTINF:" + HLS_SEGMENT_DURATION.floatValue() + ","); playlist.add(baseUrl + "/stream/segment/" + id + "/" + type + "/" + extra + "/" + i); } // Determine the duration of the final segment. double remainder = mediaElement.getDuration() % HLS_SEGMENT_DURATION; if (remainder > 0) { long i = Double.valueOf(Math.floor(mediaElement.getDuration() / HLS_SEGMENT_DURATION)).longValue(); playlist.add("#EXTINF:" + Precision.round(remainder, 1, BigDecimal.ROUND_HALF_UP) + ","); playlist.add(baseUrl + "/stream/segment/" + id + "/" + type + "/" + extra + "/" + i); } playlist.add("#EXT-X-ENDLIST"); return playlist; }
From source file:org.efaps.esjp.accounting.transaction.Calculation_Base.java
/** * Gets the JS 4 exchange rate./*from w w w . ja v a2s.c o m*/ * * @param _parameter Parameter as passed by the eFaps API * @param _parameterClone the parameter clone * @param _postfix the postfix * @return the JS 4 exchange rate * @throws EFapsException on error */ protected StringBuilder getJS4ExchangeRate(final Parameter _parameter, final Parameter _parameterClone, final String _postfix) throws EFapsException { final StringBuilder ret = new StringBuilder(); try { final String[] amounts = _parameter.getParameterValues("amount_" + _postfix); final String[] currencies = _parameter.getParameterValues("rateCurrencyLink_" + _postfix); final String[] selected = _parameter.getParameterValues("posSelect_" + _postfix); final ExchangeConfig exConf = getExchangeConfig(_parameter, null); for (int i = 0; i < selected.length; i++) { if (BooleanUtils.toBoolean(selected[i])) { final DateTime date; switch (exConf) { case DOCDATEPURCHASE: case DOCDATESALE: final Instance docInst = Instance .get(_parameter.getParameterValues("docLink_" + _postfix)[i]); if (InstanceUtils.isValid(docInst)) { final PrintQuery print = CachedPrintQuery.get4Request(docInst); print.addAttribute(CIERP.DocumentAbstract.Date); print.execute(); date = print.getAttribute(CIERP.DocumentAbstract.Date); } else { final String dateStr = _parameter.getParameterValue("date_eFapsDate"); date = DateUtil.getDateFromParameter(dateStr); } break; case TRANSDATESALE: case TRANSDATEPURCHASE: default: final String dateStr = _parameter.getParameterValue("date_eFapsDate"); date = DateUtil.getDateFromParameter(dateStr); break; } final boolean sale = ExchangeConfig.TRANSDATESALE.equals(exConf) || ExchangeConfig.DOCDATESALE.equals(exConf); final Instance periodInstance = new Period().evaluateCurrentPeriod(_parameter); final RateInfo rate = evaluateRate(_parameter, periodInstance, date, Instance.get(CIERP.Currency.getType(), currencies[i])); final DecimalFormat rateFormater = sale ? rate.getFormatter().getFrmt4SaleRateUI() : rate.getFormatter().getFrmt4RateUI(); final BigDecimal amountRate = amounts[i].isEmpty() ? BigDecimal.ZERO : (BigDecimal) rateFormater.parse(amounts[i]); final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter(); final String rateStr = sale ? rate.getSaleRateUIFrmt() : rate.getRateUIFrmt(); final String rateInStr = "" + rate.isInvert(); final String amountStr = formater.format(amountRate.setScale(12) .divide(sale ? rate.getSaleRate() : rate.getRate(), BigDecimal.ROUND_HALF_UP)); ret.append(getSetFieldValue(i, "rate_" + _postfix, rateStr)) .append(getSetFieldValue(i, "rate_" + _postfix + RateUI.INVERTEDSUFFIX, rateInStr)) .append(getSetFieldValue(i, "amountRate_" + _postfix, amountStr)); ParameterUtil.setParameterValue(_parameterClone, "rate_" + _postfix, i, rateStr); ParameterUtil.setParameterValue(_parameterClone, "rate_" + _postfix + RateUI.INVERTEDSUFFIX, i, rateInStr); ParameterUtil.setParameterValue(_parameterClone, "amountRate_" + _postfix, i, amountStr); } } } catch (final ParseException e) { throw new EFapsException(Transaction_Base.class, "update4Currency.ParseException", e); } return ret; }