List of usage examples for java.math BigDecimal ROUND_FLOOR
int ROUND_FLOOR
To view the source code for java.math BigDecimal ROUND_FLOOR.
Click Source Link
From source file:no.barentswatch.implementation.FiskInfoUtility.java
/** * Truncates a double value to the number of decimals given * //w w w . j av a 2 s . co m * @param number * The number to truncate * @param numberofDecimals * Number of decimals of the truncated number * @return */ public Double truncateDecimal(double number, int numberofDecimals) { if (number > 0) { return new BigDecimal(String.valueOf(number)).setScale(numberofDecimals, BigDecimal.ROUND_FLOOR) .doubleValue(); } else { return new BigDecimal(String.valueOf(number)).setScale(numberofDecimals, BigDecimal.ROUND_CEILING) .doubleValue(); } }
From source file:com.vmware.bdd.cli.commands.CommandsUtils.java
/** * Show a table(include table column names and table contents) by left * justifying. More specifically, the {@code columnNamesWithGetMethodNames} * argument is a map struct, the key is table column name and value is method * name list which it will be invoked by reflection. The {@code entities} * argument is traversed entity array.It is source of table data. In * addition,the method name must be each of the {@code entities} argument 's * member. The {@code spacesBeforeStart} argument is whitespace in the front * of the row.//from w w w . ja v a 2 s . c o m * <p> * * @param columnNamesWithGetMethodNames * the container of table column name and invoked method name. * @param entities * the traversed entity array. * @param spacesBeforeStart * the whitespace in the front of the row. * @throws Exception */ public static void printInTableFormat(LinkedHashMap<String, List<String>> columnNamesWithGetMethodNames, Object[] entities, String spacesBeforeStart) throws Exception { if (entities != null && entities.length > 0) { // get number of columns int columnNum = columnNamesWithGetMethodNames.size(); String[][] table = new String[entities.length + 1][columnNum]; //build table header: column names String[] tableHeader = new String[columnNum]; Set<String> columnNames = columnNamesWithGetMethodNames.keySet(); columnNames.toArray(tableHeader); //put table column names into the first row table[0] = tableHeader; //build table contents Collection<List<String>> getMethodNamesCollect = columnNamesWithGetMethodNames.values(); int i = 1; for (Object entity : entities) { int j = 0; for (List<String> getMethodNames : getMethodNamesCollect) { Object tempValue = null; int k = 0; for (String methodName : getMethodNames) { if (tempValue == null) tempValue = entity; Object value = tempValue.getClass().getMethod(methodName).invoke(tempValue); if (k == getMethodNames.size() - 1) { table[i][j] = value == null ? "" : ((value instanceof Double) ? String.valueOf( round(((Double) value).doubleValue(), 2, BigDecimal.ROUND_FLOOR)) : value.toString()); if (isJansiAvailable() && !isBlank(table[i][j])) { table[i][j] = transferEncoding(table[i][j]); } j++; } else { tempValue = value; k++; } } } i++; } printTable(table, spacesBeforeStart); } }
From source file:org.netxilia.functions.MathFunctions.java
/** * Rounds the given number to a certain number of decimal places according to valid mathematical criteria. Count * (optional) is the number of the places to which the value is to be rounded. If the count parameter is negative, * only the whole number portion is rounded. It is rounded to the place indicated by the count. * /*from w ww . j a v a 2 s .c o m*/ * @param number * @return */ public double ROUND(double number, int count) { return MathUtils.round(number, count, BigDecimal.ROUND_FLOOR); }
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/*from w w w . j av a2 s . 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:com.vmware.bdd.cli.commands.CommandsUtils.java
public static void printInTableFormat(LinkedHashMap<String, List<String>> columnNamesWithKeys, List<Map> entities, String spacesBeforeStart) throws Exception { if (MapUtils.isNotEmpty(columnNamesWithKeys)) { int columnNum = columnNamesWithKeys.size(); if (CollectionUtils.isNotEmpty(entities)) { String[][] table = new String[entities.size() + 1][columnNum]; //build table header: column names String[] tableHeader = table[0]; int rowIndex = 1; int columnIndex = 0; for (Map<String, String> entity : entities) { for (Entry<String, List<String>> columnNameEntry : columnNamesWithKeys.entrySet()) { if (tableHeader[columnIndex] == null) { tableHeader[columnIndex] = columnNameEntry.getKey(); }//from w w w . ja v a2 s . co m StringBuilder value = new StringBuilder(); for (String key : columnNameEntry.getValue()) { if (value.length() > 0) { value.append(','); } Object valueObj = entity.get(key); if (valueObj == null) { value.append(' '); } else { if (valueObj instanceof Double) { value.append(String.valueOf( round(((Double) valueObj).doubleValue(), 2, BigDecimal.ROUND_FLOOR))); } else { value.append(valueObj); } } } if (isJansiAvailable()) { table[rowIndex][columnIndex] = transferEncoding(value.toString()); } else { table[rowIndex][columnIndex] = value.toString(); } columnIndex++; } rowIndex++; } printTable(table, spacesBeforeStart); } } }
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 www . j a v a 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 {//from 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:com.shared.rides.service.ProfileService.java
public boolean calculateRating(long requestUserID, long userID, int profile, int rating) { User u = userDAO.load(userID);//from w ww . j a v a2 s . c o m // User requestUser = userDAO.load(requestUserID); // boolean isValidate = false; /* * Primero voy a ver si la asociacion entre las dos personas es mayor a * 21 dias (3 semanas), para permitir que la persona puede puntuar */ /* * Date actualDate = new Date(); List<Association> assocList = * requestUser.getAssociations(); List<Association> myRequestsList = * userDAO.getMyRequests(requestUser); * * for (int i = 0; i < assocList.size(); i++){ User assocUser = * assocList.get(i).getApplicantID(); if (assocUser.getUserId() == * userID && assocList.get(i).getState().equals(State.ACCEPTED)){ int * diff = (int) ((assocList.get(i).getDate().getTime() - * actualDate.getTime()) / (24 * 60 * 60 * 1000)); if (diff > 21){ * isValidate = true; break; } } } for (int j = 0; j < * myRequestsList.size(); j++){ //Obtengo el id del usuario al cual le * envie la peticion long userAssocId = * assocDAO.getSupplierId(myRequestsList.get(j)); if (userID == * userAssocId && * myRequestsList.get(j).getState().equals(State.ACCEPTED)){ int diff = * (int) ((assocList.get(j).getDate().getTime() - actualDate.getTime()) * / (24 * 60 * 60 * 1000)); if (diff > 21){ isValidate = true; break; } * } } */ // if(isValidate){ BigDecimal value; if (profile == 0) { float auxRating = u.getPedestrian().getRating(); auxRating = (auxRating + rating) / 2; u.getPedestrian().setRating(Math.round(auxRating * 100) / 100); } else { float auxRating = u.getDriver().getRating(); auxRating = (auxRating + rating) / 2; value = new BigDecimal(String.valueOf(auxRating)).setScale(2, BigDecimal.ROUND_FLOOR); u.getDriver().setRating(value.floatValue()); } userDAO.update(u); return true; // } // return false; }
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 *//*w w w . j a v a 2 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); }