List of usage examples for java.math BigDecimal ROUND_CEILING
int ROUND_CEILING
To view the source code for java.math BigDecimal ROUND_CEILING.
Click Source Link
From source file:org.kalypso.ui.wizards.results.ResultSldHelper.java
private static void configurePolygonSymbolizer(final SurfacePolygonSymbolizer symbolizer, final BigDecimal minValue, final BigDecimal maxValue) throws FilterEvaluationException { final PolygonColorMap templateColorMap = symbolizer.getColorMap(); final PolygonColorMap newColorMap = new PolygonColorMap_Impl(); // retrieve stuff from template-entries final PolygonColorMapEntry fromEntry = templateColorMap.findEntry("from", null); //$NON-NLS-1$ final PolygonColorMapEntry toEntry = templateColorMap.findEntry("to", null); //$NON-NLS-1$ // Fill/*www. j a va 2s.c o m*/ final Color fromPolygonColor = fromEntry.getFill().getFill(null); final Color toPolygonColor = toEntry.getFill().getFill(null); final double polygonOpacity = fromEntry.getFill().getOpacity(null); // Stroke final Color fromLineColor = fromEntry.getStroke().getStroke(null); final Color toLineColor = toEntry.getStroke().getStroke(null); final double lineOpacity = fromEntry.getStroke().getOpacity(null); // step width final double stepWidth = fromEntry.getTo(null); // scale of the step width final BigDecimal setScale = new BigDecimal(fromEntry.getFrom(null)).setScale(0, BigDecimal.ROUND_FLOOR); final int stepWidthScale = setScale.intValue(); // get rounded values below min and above max (rounded by first decimal) // as a first try we will generate isareas by using class steps of 0.1 // later, the classes will be created by using user defined class steps. // for that we fill an array of calculated (later user defined values) from max to min final BigDecimal minDecimal = minValue.setScale(1, BigDecimal.ROUND_FLOOR); final BigDecimal maxDecimal = maxValue.setScale(1, BigDecimal.ROUND_CEILING); final BigDecimal polygonStepWidth = new BigDecimal(stepWidth).setScale(stepWidthScale, BigDecimal.ROUND_FLOOR); int numOfClasses = (maxDecimal.subtract(minDecimal).divide(polygonStepWidth)).intValue(); // set to provide more them 1 or 0 classes. in such cases the color map will not be created, that results error. if (numOfClasses < 2) { numOfClasses = (maxDecimal.subtract(minDecimal).divide(polygonStepWidth.divide(new BigDecimal(4)))) .intValue(); } for (int currentClass = 0; currentClass < numOfClasses; currentClass++) { final double fromValue = minDecimal.doubleValue() + currentClass * polygonStepWidth.doubleValue(); final double toValue = minDecimal.doubleValue() + (currentClass + 1) * polygonStepWidth.doubleValue(); // Stroke Color lineColor; if (fromLineColor == toLineColor) lineColor = fromLineColor; else lineColor = interpolateColor(fromLineColor, toLineColor, currentClass, numOfClasses); // Fill final Color polygonColor = interpolateColor(fromPolygonColor, toPolygonColor, currentClass, numOfClasses); lineColor = polygonColor; final Stroke stroke = StyleFactory.createStroke(lineColor, lineOpacity, 1); final Fill fill = StyleFactory.createFill(polygonColor, polygonOpacity); final ParameterValueType label = StyleFactory.createParameterValueType("Isoflche " + currentClass); //$NON-NLS-1$ final ParameterValueType from = StyleFactory.createParameterValueType(fromValue); final ParameterValueType to = StyleFactory.createParameterValueType(toValue); final PolygonColorMapEntry colorMapEntry = new PolygonColorMapEntry_Impl(fill, stroke, label, from, to); newColorMap.addColorMapClass(colorMapEntry); } symbolizer.setColorMap(newColorMap); }
From source file:org.yes.cart.payment.impl.PayPalButtonPaymentGatewayImpl.java
/** * {@inheritDoc}//from ww w. j a v a 2 s .co m */ public String getHtmlForm(final String cardHolderName, final String locale, final BigDecimal amount, final String currencyCode, final String orderReference, final Payment payment) { final StringBuilder form = new StringBuilder(); form.append(getHiddenFieldValue("button", "buynow")); form.append(getHiddenFieldValue("cmd", "_cart")); form.append(getHiddenFieldValue("upload", "1")); form.append(getHiddenFieldValue("paymentaction", "sale")); form.append(getHiddenFieldParam("business", PPB_USER)); form.append(getHiddenFieldParam("env", PPB_ENVIRONMENT)); form.append(getHiddenFieldParam("notify_url", PPB_NOTIFYURL)); form.append(getHiddenFieldParam("return", PPB_RETURNURL)); form.append(getHiddenFieldParam("cancel_return", PPB_CANCELURL)); form.append(getHiddenFieldValue("currency_code", currencyCode)); form.append(getHiddenFieldValue("invoice", orderReference)); form.append(getHiddenFieldValue("custom", orderReference)); form.append(getHiddenFieldValue("lc", paymentLocaleTranslator.translateLocale(this, locale))); form.append(getHiddenFieldValue("charset", "UTF-8")); if (payment.getBillingAddress() != null) { form.append(getHiddenFieldValue("first_name", payment.getBillingAddress().getFirstname())); form.append(getHiddenFieldValue("last_name", payment.getBillingAddress().getLastname())); form.append(getHiddenFieldValue("email", payment.getBillingEmail())); } if (payment.getShippingAddress() != null) { form.append(getHiddenFieldValue("address1", payment.getShippingAddress().getAddrline1())); form.append(getHiddenFieldValue("address2", payment.getShippingAddress().getAddrline2())); form.append(getHiddenFieldValue("city", payment.getShippingAddress().getCity())); form.append(getHiddenFieldValue("country", payment.getShippingAddress().getCountryCode())); form.append(getHiddenFieldValue("state", payment.getShippingAddress().getStateCode())); form.append(getHiddenFieldValue("zip", payment.getShippingAddress().getPostcode())); form.append(getHiddenFieldValue("address_override", "1")); } BigDecimal totalItems = Total.ZERO; int i = 1; for (final PaymentLine item : payment.getOrderItems()) { form.append(getHiddenFieldValue("item_name_" + i, item.getSkuName())); form.append(getHiddenFieldValue("item_number_" + i, item.getSkuCode())); // PayPal can only handle whole values, so do ceil final BigDecimal ppQty = item.getQuantity().setScale(0, BigDecimal.ROUND_CEILING); form.append(getHiddenFieldValue("quantity_" + i, ppQty.toPlainString())); final BigDecimal taxUnit = MoneyUtils.isFirstBiggerThanSecond(item.getTaxAmount(), Total.ZERO) ? item.getTaxAmount().divide(item.getQuantity(), Total.ZERO.scale(), RoundingMode.HALF_UP) : Total.ZERO; final BigDecimal itemAmount = item.getUnitPrice().subtract(taxUnit); form.append(getHiddenFieldValue("amount_" + i, itemAmount.toPlainString())); // form.append(getHiddenFieldValue("tax_" + i, taxUnit.setScale(Total.ZERO.scale(), RoundingMode.HALF_UP).toPlainString())); if (ppQty.compareTo(item.getQuantity()) != 0) { // If we have decimals in qty need to save it as item option form.append(getHiddenFieldValue("on0_" + i, "x")); form.append(getHiddenFieldValue("on1_" + i, item.getQuantity().toPlainString())); } i++; totalItems = totalItems.add(itemAmount.multiply(item.getQuantity())); } final BigDecimal payNet = payment.getPaymentAmount().subtract(payment.getTaxAmount()); if (payNet.compareTo(totalItems) < 0) { form.append(getHiddenFieldValue("discount_amount_cart", totalItems.subtract(payNet) .setScale(Total.ZERO.scale(), RoundingMode.HALF_UP).toPlainString())); } form.append(getHiddenFieldValue("tax_cart", payment.getTaxAmount().toPlainString())); return form.toString(); }
From source file:org.apache.ofbiz.shipment.thirdparty.usps.UspsServices.java
public static Map<String, Object> uspsRateInquire(DispatchContext dctx, Map<String, ? extends Object> context) { Delegator delegator = dctx.getDelegator(); String shipmentGatewayConfigId = (String) context.get("shipmentGatewayConfigId"); String resource = (String) context.get("configProps"); Locale locale = (Locale) context.get("locale"); // check for 0 weight BigDecimal shippableWeight = (BigDecimal) context.get("shippableWeight"); if (shippableWeight.compareTo(BigDecimal.ZERO) == 0) { // TODO: should we return an error, or $0.00 ? return ServiceUtil.returnFailure(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsShippableWeightMustGreaterThanZero", locale)); }//from w ww. ja va 2 s .c om // get the origination ZIP String originationZip = null; GenericValue productStore = ProductStoreWorker.getProductStore(((String) context.get("productStoreId")), delegator); if (productStore != null && productStore.get("inventoryFacilityId") != null) { GenericValue facilityContactMech = ContactMechWorker.getFacilityContactMechByPurpose(delegator, productStore.getString("inventoryFacilityId"), UtilMisc.toList("SHIP_ORIG_LOCATION", "PRIMARY_LOCATION")); if (facilityContactMech != null) { try { GenericValue shipFromAddress = EntityQuery.use(delegator).from("PostalAddress") .where("contactMechId", facilityContactMech.getString("contactMechId")).queryOne(); if (shipFromAddress != null) { originationZip = shipFromAddress.getString("postalCode"); } } catch (GenericEntityException e) { Debug.logError(e, module); } } } if (UtilValidate.isEmpty(originationZip)) { return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsUnableDetermineOriginationZip", locale)); } // get the destination ZIP String destinationZip = null; String shippingContactMechId = (String) context.get("shippingContactMechId"); if (UtilValidate.isNotEmpty(shippingContactMechId)) { try { GenericValue shipToAddress = EntityQuery.use(delegator).from("PostalAddress") .where("contactMechId", shippingContactMechId).queryOne(); if (shipToAddress != null) { if (!domesticCountries.contains(shipToAddress.getString("countryGeoId"))) { return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsRateInquiryOnlyInUsDestinations", locale)); } destinationZip = shipToAddress.getString("postalCode"); } } catch (GenericEntityException e) { Debug.logError(e, module); } } if (UtilValidate.isEmpty(destinationZip)) { return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsUnableDetermineDestinationZip", locale)); } // get the service code String serviceCode = null; try { GenericValue carrierShipmentMethod = EntityQuery.use(delegator).from("CarrierShipmentMethod") .where("shipmentMethodTypeId", (String) context.get("shipmentMethodTypeId"), "partyId", (String) context.get("carrierPartyId"), "roleTypeId", (String) context.get("carrierRoleTypeId")) .queryOne(); if (carrierShipmentMethod != null) { serviceCode = carrierShipmentMethod.getString("carrierServiceCode").toUpperCase(); } } catch (GenericEntityException e) { Debug.logError(e, module); } if (UtilValidate.isEmpty(serviceCode)) { return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsUnableDetermineServiceCode", locale)); } // create the request document Document requestDocument = createUspsRequestDocument("RateV2Request", true, delegator, shipmentGatewayConfigId, resource); // TODO: 70 lb max is valid for Express, Priority and Parcel only - handle other methods BigDecimal maxWeight = new BigDecimal("70"); String maxWeightStr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "maxEstimateWeight", resource, "shipment.usps.max.estimate.weight", "70"); try { maxWeight = new BigDecimal(maxWeightStr); } catch (NumberFormatException e) { Debug.logWarning( "Error parsing max estimate weight string [" + maxWeightStr + "], using default instead", module); maxWeight = new BigDecimal("70"); } List<Map<String, Object>> shippableItemInfo = UtilGenerics.checkList(context.get("shippableItemInfo")); List<Map<String, BigDecimal>> packages = ShipmentWorker.getPackageSplit(dctx, shippableItemInfo, maxWeight); boolean isOnePackage = packages.size() == 1; // use shippableWeight if there's only one package // TODO: Up to 25 packages can be included per request - handle more than 25 for (ListIterator<Map<String, BigDecimal>> li = packages.listIterator(); li.hasNext();) { Map<String, BigDecimal> packageMap = li.next(); BigDecimal packageWeight = isOnePackage ? shippableWeight : ShipmentWorker.calcPackageWeight(dctx, packageMap, shippableItemInfo, BigDecimal.ZERO); if (packageWeight.compareTo(BigDecimal.ZERO) == 0) { continue; } Element packageElement = UtilXml.addChildElement(requestDocument.getDocumentElement(), "Package", requestDocument); packageElement.setAttribute("ID", String.valueOf(li.nextIndex() - 1)); // use zero-based index (see examples) UtilXml.addChildElementValue(packageElement, "Service", serviceCode, requestDocument); UtilXml.addChildElementValue(packageElement, "ZipOrigination", StringUtils.substring(originationZip, 0, 5), requestDocument); UtilXml.addChildElementValue(packageElement, "ZipDestination", StringUtils.substring(destinationZip, 0, 5), requestDocument); BigDecimal weightPounds = packageWeight.setScale(0, BigDecimal.ROUND_FLOOR); // for Parcel post, the weight must be at least 1 lb if ("PARCEL".equals(serviceCode.toUpperCase()) && (weightPounds.compareTo(BigDecimal.ONE) < 0)) { weightPounds = BigDecimal.ONE; packageWeight = BigDecimal.ZERO; } // (packageWeight % 1) * 16 (Rounded up to 0 dp) BigDecimal weightOunces = packageWeight.remainder(BigDecimal.ONE).multiply(new BigDecimal("16")) .setScale(0, BigDecimal.ROUND_CEILING); UtilXml.addChildElementValue(packageElement, "Pounds", weightPounds.toPlainString(), requestDocument); UtilXml.addChildElementValue(packageElement, "Ounces", weightOunces.toPlainString(), requestDocument); // TODO: handle other container types, package sizes, and machinable packages // IMPORTANT: Express or Priority Mail will fail if you supply a Container tag: you will get a message like // Invalid container type. Valid container types for Priority Mail are Flat Rate Envelope and Flat Rate Box. /* This is an official response from the United States Postal Service: The <Container> tag is used to specify the flat rate mailing options, or the type of large or oversized package being mailed. If you are wanting to get regular Express Mail rates, leave the <Container> tag empty, or do not include it in the request at all. */ if ("Parcel".equalsIgnoreCase(serviceCode)) { UtilXml.addChildElementValue(packageElement, "Container", "None", requestDocument); } UtilXml.addChildElementValue(packageElement, "Size", "REGULAR", requestDocument); UtilXml.addChildElementValue(packageElement, "Machinable", "false", requestDocument); } // send the request Document responseDocument = null; try { responseDocument = sendUspsRequest("RateV2", requestDocument, delegator, shipmentGatewayConfigId, resource, locale); } catch (UspsRequestException e) { Debug.logInfo(e, module); return ServiceUtil.returnError( UtilProperties.getMessage(resourceError, "FacilityShipmentUspsRateDomesticSendingError", UtilMisc.toMap("errorString", e.getMessage()), locale)); } if (responseDocument == null) { return ServiceUtil.returnError( UtilProperties.getMessage(resourceError, "FacilityShipmentRateNotAvailable", locale)); } List<? extends Element> rates = UtilXml.childElementList(responseDocument.getDocumentElement(), "Package"); if (UtilValidate.isEmpty(rates)) { return ServiceUtil.returnError( UtilProperties.getMessage(resourceError, "FacilityShipmentRateNotAvailable", locale)); } BigDecimal estimateAmount = BigDecimal.ZERO; for (Element packageElement : rates) { try { Element postageElement = UtilXml.firstChildElement(packageElement, "Postage"); BigDecimal packageAmount = new BigDecimal(UtilXml.childElementValue(postageElement, "Rate")); estimateAmount = estimateAmount.add(packageAmount); } catch (NumberFormatException e) { Debug.logInfo(e, module); } } Map<String, Object> result = ServiceUtil.returnSuccess(); result.put("shippingEstimateAmount", estimateAmount); return result; }
From source file:ch.algotrader.service.OptionServiceImpl.java
private BigDecimal roundOptionStrikeToNextN(BigDecimal spot, BigDecimal n, OptionType type) { if (OptionType.CALL.equals(type)) { // increase by strikeOffset and round to upper n return RoundUtil.roundToNextN(spot, n, BigDecimal.ROUND_CEILING); } else {// ww w. j av a 2 s .c o m // reduce by strikeOffset and round to lower n return RoundUtil.roundToNextN(spot, n, BigDecimal.ROUND_FLOOR); } }
From source file:org.egov.ptis.web.controller.masters.taxrates.TaxRatesController.java
private void addTotalTaxHeadsToModel(Model model) { BigDecimal totRsdTax = BigDecimal.ZERO; BigDecimal totNRsdTax = BigDecimal.ZERO; BigDecimal eduTax = BigDecimal.ZERO; for (EgDemandReasonDetails drd : taxRatesService.getTaxRates()) { if (drd.getEgDemandReasonMaster().getCode().equals(TOTAL_TAX_RESD)) totRsdTax = drd.getPercentage(); if (drd.getEgDemandReasonMaster().getCode().equals(TOTAL_TAX_NONRESD)) totNRsdTax = drd.getPercentage(); if (drd.getEgDemandReasonMaster().getCode().equals(EDUCATIONAL_TAX)) eduTax = drd.getPercentage(); }/*from w w w .j a va2s.c om*/ totRsdTax = totRsdTax.add(eduTax); totNRsdTax = totNRsdTax.add(eduTax); model.addAttribute("genTaxResd", totRsdTax.setScale(2, BigDecimal.ROUND_CEILING)); model.addAttribute("genTaxNonResd", totNRsdTax.setScale(2, BigDecimal.ROUND_CEILING)); }
From source file:science.atlarge.graphalytics.graphmat.GraphmatPlatform.java
@Override public BenchmarkMetrics finalize(RunSpecification runSpecification) { stopPlatformLogging();//from w w w . ja va 2 s . c o m BenchmarkRunSetup benchmarkRunSetup = runSpecification.getBenchmarkRunSetup(); String logs = FileUtil.readFile(benchmarkRunSetup.getLogDir().resolve("platform").resolve("driver.logs")); Long startTime = null; Long endTime = null; for (String line : logs.split("\n")) { try { if (line.contains("Processing starts at: ")) { String[] lineParts = line.split("\\s+"); startTime = Long.parseLong(lineParts[lineParts.length - 1]); } if (line.contains("Processing ends at: ")) { String[] lineParts = line.split("\\s+"); endTime = Long.parseLong(lineParts[lineParts.length - 1]); } } catch (Exception e) { LOG.error(String.format("Cannot parse line: %s", line)); e.printStackTrace(); } } if (startTime != null && endTime != null) { BenchmarkMetrics metrics = new BenchmarkMetrics(); Long procTimeMS = new Long(endTime - startTime); BigDecimal procTimeS = (new BigDecimal(procTimeMS)).divide(new BigDecimal(1000), 3, BigDecimal.ROUND_CEILING); metrics.setProcessingTime(new BenchmarkMetric(procTimeS, "s")); return metrics; } else { return new BenchmarkMetrics(); } }
From source file:jp.terasoluna.fw.web.taglib.DecimalTag.java
/** * ^O]Jn?\bh?B//from w ww . ja v a 2 s . c o m * * @return ???w?B? <code>SKIP_BODY</code> * @throws JspException JSPO */ @Override public int doStartTag() throws JspException { Object value = this.value; if (value == null) { // bean???Av?beanbNAbv // ???A^?[ if (ignore) { if (TagUtil.lookup(pageContext, name, scope) == null) { return SKIP_BODY; // ?o } } // v?v?peBlbNAbv value = TagUtil.lookup(pageContext, name, property, scope); if (value == null) { return SKIP_BODY; // ?o } } // v?peBlString^xBigDecimal BigDecimal bd = null; if (value instanceof String) { String trimed = StringUtil.rtrim((String) value); if ("".equals(trimed)) { return SKIP_BODY; // ?o } bd = new BigDecimal(trimed); } else if (value instanceof BigDecimal) { bd = (BigDecimal) value; } else { return SKIP_BODY; // ?o } // ??_?w?? if (scale >= 0) { // round???[h?s?i???l?j if (round != null) { if ("ROUND_FLOOR".equalsIgnoreCase(round)) { bd = bd.setScale(scale, BigDecimal.ROUND_FLOOR); } else if ("ROUND_CEILING".equalsIgnoreCase(round)) { bd = bd.setScale(scale, BigDecimal.ROUND_CEILING); } else if ("ROUND_HALF_UP".equalsIgnoreCase(round)) { bd = bd.setScale(scale, BigDecimal.ROUND_HALF_UP); } else { log.error("Please set a rounding mode"); throw new IllegalArgumentException("Please set a rounding mode"); } } else { bd = bd.setScale(scale, BigDecimal.ROUND_HALF_UP); } } // tH?[}bg DecimalFormat df = new DecimalFormat(pattern); String output = df.format(bd); if (id != null) { // idw?AXNveBO?p // y?[WXR?[vZbg?B pageContext.setAttribute(id, output); } else { // idw?Av?peBlC^vg // ?BK?tB^?B if (filter) { TagUtil.write(pageContext, TagUtil.filter(output)); } else { TagUtil.write(pageContext, output); } } return SKIP_BODY; }
From source file:org.kalypso.ui.wizards.results.ResultSldHelper.java
/** * sets the parameters for the colormap of an isoline *///from www . j a va2 s . c o m private static void configureLineSymbolizer(final SurfaceLineSymbolizer symbolizer, final BigDecimal minValue, final BigDecimal maxValue) throws FilterEvaluationException { final LineColorMap templateColorMap = symbolizer.getColorMap(); final LineColorMap newColorMap = new LineColorMap_Impl(); // retrieve stuff from template-entries final LineColorMapEntry fromEntry = templateColorMap.findEntry("from", null); //$NON-NLS-1$ final LineColorMapEntry toEntry = templateColorMap.findEntry("to", null); //$NON-NLS-1$ final LineColorMapEntry fatEntry = templateColorMap.findEntry("fat", null); //$NON-NLS-1$ final Color fromColor = fromEntry.getStroke().getStroke(null); final Color toColor = toEntry.getStroke().getStroke(null); final double opacity = fromEntry.getStroke().getOpacity(null); final double normalWidth = fromEntry.getStroke().getWidth(null); final double fatWidth = fatEntry.getStroke().getWidth(null); // defines which isolines are drawn with a fat line final double fatValue = fatEntry.getQuantity(null); // TODO: get setep / scale from quantity // get rounded values below min and above max (rounded by first decimal) // as a first try we will generate isolines using class steps of 0.1 // later, the classes will be done by using user defined class steps. // for that we fill an array of calculated (later user defined values) from max to min final BigDecimal minDecimal = minValue.setScale(1, BigDecimal.ROUND_FLOOR); final BigDecimal maxDecimal = maxValue.setScale(1, BigDecimal.ROUND_CEILING); final BigDecimal stepWidth = new BigDecimal(0.1).setScale(1, BigDecimal.ROUND_HALF_UP); final int numOfClasses = (maxDecimal.subtract(minDecimal).divide(stepWidth)).intValue() + 1; for (int currentClass = 0; currentClass < numOfClasses; currentClass++) { final double currentValue = minDecimal.doubleValue() + currentClass * stepWidth.doubleValue(); Color lineColor; if (fromColor == toColor) lineColor = fromColor; else lineColor = interpolateColor(fromColor, toColor, currentClass, numOfClasses); final double strokeWidth; if (currentValue % fatValue == 0) strokeWidth = fatWidth; else strokeWidth = normalWidth; final Stroke stroke = StyleFactory.createStroke(lineColor, strokeWidth, opacity); final ParameterValueType label = StyleFactory.createParameterValueType("Isolinie " + currentClass); //$NON-NLS-1$ final ParameterValueType quantity = StyleFactory.createParameterValueType(currentValue); final LineColorMapEntry colorMapEntry = new LineColorMapEntry_Impl(stroke, label, quantity); newColorMap.addColorMapClass(colorMapEntry); } symbolizer.setColorMap(newColorMap); }
From source file:science.atlarge.graphalytics.graphmat.GraphmatPlatform.java
@Override public void enrichMetrics(BenchmarkRunResult benchmarkRunResult, Path arcDirectory) { try {/*from w w w. j av a 2 s . co m*/ PlatformArchive platformArchive = PlatformArchive.readArchive(arcDirectory); JSONObject processGraph = platformArchive.operation("ProcessGraph"); BenchmarkMetrics metrics = benchmarkRunResult.getMetrics(); Integer procTimeMS = Integer.parseInt(platformArchive.info(processGraph, "Duration")); BigDecimal procTimeS = (new BigDecimal(procTimeMS)).divide(new BigDecimal(1000), 3, BigDecimal.ROUND_CEILING); metrics.setProcessingTime(new BenchmarkMetric(procTimeS, "s")); } catch (Exception e) { LOG.error("Failed to enrich metrics."); } }
From source file:Armadillo.Analytics.Base.Precision.java
/** * Rounds the given non-negative value to the "nearest" integer. Nearest is * determined by the rounding method specified. Rounding methods are defined * in {@link BigDecimal}./*from w w w. j a v a 2 s.c om*/ * * @param unscaled Value to round. * @param sign Sign of the original, scaled value. * @param roundingMethod Rounding method, as defined in {@link BigDecimal}. * @return the rounded value. * @throws MathArithmeticException if an exact operation is required but result is not exact * @throws MathIllegalArgumentException if {@code roundingMethod} is not a valid rounding method. * @since 1.1 (previously in {@code MathUtils}, moved as of version 3.0) */ private static double roundUnscaled(double unscaled, double sign, int roundingMethod) throws MathArithmeticException, MathIllegalArgumentException { switch (roundingMethod) { case BigDecimal.ROUND_CEILING: if (sign == -1) { unscaled = FastMath.floor(FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY)); } else { unscaled = FastMath.ceil(FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY)); } break; case BigDecimal.ROUND_DOWN: unscaled = FastMath.floor(FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY)); break; case BigDecimal.ROUND_FLOOR: if (sign == -1) { unscaled = FastMath.ceil(FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY)); } else { unscaled = FastMath.floor(FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY)); } break; case BigDecimal.ROUND_HALF_DOWN: { unscaled = FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY); double fraction = unscaled - FastMath.floor(unscaled); if (fraction > 0.5) { unscaled = FastMath.ceil(unscaled); } else { unscaled = FastMath.floor(unscaled); } break; } case BigDecimal.ROUND_HALF_EVEN: { double fraction = unscaled - FastMath.floor(unscaled); if (fraction > 0.5) { unscaled = FastMath.ceil(unscaled); } else if (fraction < 0.5) { unscaled = FastMath.floor(unscaled); } else { // The following equality test is intentional and needed for rounding purposes if (FastMath.floor(unscaled) / 2.0 == FastMath.floor(Math.floor(unscaled) / 2.0)) { // even unscaled = FastMath.floor(unscaled); } else { // odd unscaled = FastMath.ceil(unscaled); } } break; } case BigDecimal.ROUND_HALF_UP: { unscaled = FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY); double fraction = unscaled - FastMath.floor(unscaled); if (fraction >= 0.5) { unscaled = FastMath.ceil(unscaled); } else { unscaled = FastMath.floor(unscaled); } break; } case BigDecimal.ROUND_UNNECESSARY: if (unscaled != FastMath.floor(unscaled)) { throw new MathArithmeticException(); } break; case BigDecimal.ROUND_UP: unscaled = FastMath.ceil(FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY)); break; default: throw new MathIllegalArgumentException(LocalizedFormats.INVALID_ROUNDING_METHOD, roundingMethod, "ROUND_CEILING", BigDecimal.ROUND_CEILING, "ROUND_DOWN", BigDecimal.ROUND_DOWN, "ROUND_FLOOR", BigDecimal.ROUND_FLOOR, "ROUND_HALF_DOWN", BigDecimal.ROUND_HALF_DOWN, "ROUND_HALF_EVEN", BigDecimal.ROUND_HALF_EVEN, "ROUND_HALF_UP", BigDecimal.ROUND_HALF_UP, "ROUND_UNNECESSARY", BigDecimal.ROUND_UNNECESSARY, "ROUND_UP", BigDecimal.ROUND_UP); } return unscaled; }