List of usage examples for java.math RoundingMode DOWN
RoundingMode DOWN
To view the source code for java.math RoundingMode DOWN.
Click Source Link
From source file:com.cs528.style.style.weather.WeatherActivity.java
private void updateTodayWeatherUI() { String city = todayWeather.getCity(); String country = todayWeather.getCountry(); getSupportActionBar().setTitle(city + (country.isEmpty() ? "" : ", " + country)); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this); String temperature = todayWeather.getTemperature(); if (sp.getString("unit", "C").equals("C")) { temperature = Float.parseFloat(temperature) - 273.15 + ""; }//from w w w. j av a 2 s . c om if (sp.getString("unit", "C").equals("F")) { temperature = (((9 * (Float.parseFloat(temperature) - 273.15)) / 5) + 32) + ""; } double wind = Double.parseDouble(todayWeather.getWind()); if (sp.getString("speedUnit", "m/s").equals("kph")) { wind = wind * 3.59999999712; } if (sp.getString("speedUnit", "m/s").equals("mph")) { wind = wind * 2.23693629205; } double pressure = Double.parseDouble(todayWeather.getPressure()); if (sp.getString("pressureUnit", "hPa").equals("kPa")) { pressure = pressure / 10; } if (sp.getString("pressureUnit", "hPa").equals("mm Hg")) { pressure = pressure * 0.750061561303; } if (new BigDecimal(temperature).setScale(0, RoundingMode.DOWN).intValue() == 0) { temperature = "0"; } else { temperature = temperature.substring(0, temperature.indexOf(".") + 2); } todayTemperature.setText(temperature + " " + sp.getString("unit", "C")); if (Float.parseFloat(todayWeather.getRain()) > 0.1) { todayDescription.setText(todayWeather.getDescription().substring(0, 1).toUpperCase() + todayWeather.getDescription().substring(1) + " (" + todayWeather.getRain().substring(0, todayWeather.getRain().indexOf(".") + 2) + " mm)"); } else { todayDescription.setText(todayWeather.getDescription().substring(0, 1).toUpperCase() + todayWeather.getDescription().substring(1)); } todayWind.setText(getString(R.string.wind) + ": " + (wind + "").substring(0, (wind + "").indexOf(".") + 2) + " " + localize(sp, "speedUnit", "m/s") + (todayWeather.isWindDirectionAvailable() ? " " + getWindDirectionString(sp, this, todayWeather) : "")); todayPressure.setText( getString(R.string.pressure) + ": " + (pressure + "").substring(0, (pressure + "").indexOf(".") + 2) + " " + localize(sp, "pressureUnit", "hPa")); todayHumidity.setText(getString(R.string.humidity) + ": " + todayWeather.getHumidity() + " %"); // todayIcon.setText(todayWeather.getIcon()); }
From source file:com.lcl.thumbweather.MainActivity.java
private void updateTodayWeatherUI() { String city = todayWeather.getCity(); Log.d("402-LCL-", "updateTodayWeatherUI:city = " + city); String country = todayWeather.getCountry(); DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(getApplicationContext()); Log.d("402-LCL-", "cityIS:" + city + (country.isEmpty() ? "" : ", " + country)); cityIs.setText(city + (country.isEmpty() ? "" : ", " + country)); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this); String temperature = todayWeather.getTemperature(); if (sp.getString("unit", "C").equals("C")) { temperature = Float.parseFloat(temperature) - 273.15 + ""; }/*from www . j ava 2s . co m*/ if (sp.getString("unit", "C").equals("F")) { temperature = (((9 * (Float.parseFloat(temperature) - 273.15)) / 5) + 32) + ""; } double wind = Double.parseDouble(todayWeather.getWind()); if (sp.getString("speedUnit", "m/s").equals("kph")) { wind = wind * 3.59999999712; } if (sp.getString("speedUnit", "m/s").equals("mph")) { wind = wind * 2.23693629205; } double pressure = Double.parseDouble(todayWeather.getPressure()); if (sp.getString("pressureUnit", "hPa").equals("kPa")) { pressure = pressure / 10; } if (sp.getString("pressureUnit", "hPa").equals("mm Hg")) { pressure = pressure * 0.750061561303; } if (new BigDecimal(temperature).setScale(0, RoundingMode.DOWN).intValue() == 0) { temperature = "0"; } else { temperature = temperature.substring(0, temperature.indexOf(".") + 2); } todayTemperature.setText(temperature + " " + sp.getString("unit", "C")); if (todayWeather.getRain() != null) { if (Float.parseFloat(todayWeather.getRain()) > 0.1) { todayDescription.setText(todayWeather.getDescription().substring(0, 1).toUpperCase() + todayWeather.getDescription().substring(1) + " (" + todayWeather.getRain().substring(0, todayWeather.getRain().indexOf(".") + 2) + " mm)"); } else { todayDescription.setText(todayWeather.getDescription().substring(0, 1).toUpperCase() + todayWeather.getDescription().substring(1)); } todayWind.setText( getString(R.string.wind) + ": " + (wind + "").substring(0, (wind + "").indexOf(".") + 2) + " " + localize(sp, "speedUnit", "m/s") + (todayWeather.isWindDirectionAvailable() ? " " + getWindDirectionString(sp, this, todayWeather) : "")); todayPressure.setText(getString(R.string.pressure) + ": " + (pressure + "").substring(0, (pressure + "").indexOf(".") + 2) + " " + localize(sp, "pressureUnit", "hPa")); todayHumidity.setText(getString(R.string.humidity) + ": " + todayWeather.getHumidity() + " %"); todaySunrise.setText(getString(R.string.sunrise) + ": " + timeFormat.format(todayWeather.getSunrise())); todaySunset.setText(getString(R.string.sunset) + ": " + timeFormat.format(todayWeather.getSunset())); todayIcon.setText(todayWeather.getIcon()); } }
From source file:it.newfammulfin.api.EntryResource.java
@POST @Consumes("text/csv") @Produces(MediaType.TEXT_PLAIN)/* w w w .j a v a 2 s .c o m*/ public Response importFromCsv(String csvData, @DefaultValue("false") @QueryParam("invertSign") final boolean invertSign) { final Group group = (Group) requestContext.getProperty(GroupRetrieverRequestFilter.GROUP); final Map<String, Key<Chapter>> chapterStringsMap = new HashMap<>(); final List<CSVRecord> records; try { records = CSVParser.parse(csvData, CSVFormat.DEFAULT.withHeader()).getRecords(); } catch (IOException e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(String.format("Unexpected %s: %s.", e.getClass().getSimpleName(), e.getMessage())) .build(); } //check users final Set<String> userIds = new HashSet<>(); for (String columnName : records.get(0).toMap().keySet()) { if (columnName.startsWith("by:")) { String userId = columnName.replaceFirst("by:", ""); if (!group.getUsersMap().keySet().contains(Key.create(RegisteredUser.class, userId))) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(String.format("User %s not found in this group.", userId)).build(); } userIds.add(userId); } } //build chapters final Set<String> chapterStringsSet = new HashSet<>(); for (CSVRecord record : records) { chapterStringsSet.add(record.get("chapters")); } final List<Key<?>> createdKeys = new ArrayList<>(); try { OfyService.ofy().transact(new Work<List<Key<?>>>() { @Override public List<Key<?>> run() { for (String chapterStrings : chapterStringsSet) { List<String> pieces = Arrays.asList(chapterStrings.split(CSV_CHAPTERS_SEPARATOR)); Key<Chapter> parentChapterKey = null; for (int i = 0; i < pieces.size(); i++) { String partialChapterString = Joiner.on(CSV_CHAPTERS_SEPARATOR) .join(pieces.subList(0, i + 1)); Key<Chapter> chapterKey = chapterStringsMap.get(partialChapterString); if (chapterKey == null) { chapterKey = OfyService.ofy().load().type(Chapter.class).ancestor(group) .filter("name", pieces.get(i)).filter("parentChapterKey", parentChapterKey) .keys().first().now(); chapterStringsMap.put(partialChapterString, chapterKey); } if (chapterKey == null) { Chapter chapter = new Chapter(pieces.get(i), Key.create(group), parentChapterKey); OfyService.ofy().save().entity(chapter).now(); chapterKey = Key.create(chapter); createdKeys.add(chapterKey); LOG.info(String.format("%s created.", chapter)); } chapterStringsMap.put(partialChapterString, chapterKey); parentChapterKey = chapterKey; } } //build entries DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/YY"); Key<Group> groupKey = Key.create(group); for (CSVRecord record : records) { Entry entry = new Entry(); entry.setGroupKey(groupKey); entry.setDate(LocalDate.parse(record.get("date"), formatter)); entry.setAmount(Money.of(CurrencyUnit.of(record.get("currency").toUpperCase()), (invertSign ? -1 : 1) * Double.parseDouble(record.get("value")))); if (!record.get("chapters").isEmpty()) { entry.setChapterKey(chapterStringsMap.get(record.get("chapters"))); } entry.setPayee(record.get("payee")); for (String tag : record.get("tags").split(CSV_TAGS_SEPARATOR)) { if (!tag.trim().isEmpty()) { entry.getTags().add(tag); } } entry.setDescription(record.get("description")); entry.setNote(record.get("notes")); int scale = Math.max(DEFAULT_SHARE_SCALE, entry.getAmount().getScale()); //by shares for (String userId : userIds) { String share = record.get("by:" + userId); double value; if (share.contains("%")) { entry.setByPercentage(true); value = Double.parseDouble(share.replace("%", "")); value = entry.getAmount().getAmount().doubleValue() * value / 100d; } else { value = (invertSign ? -1 : 1) * Double.parseDouble(share); } entry.getByShares().put(Key.create(RegisteredUser.class, userId), BigDecimal.valueOf(value).setScale(scale, RoundingMode.DOWN)); } boolean equalByShares = checkAndBalanceZeroShares(entry.getByShares(), entry.getAmount().getAmount()); entry.setByPercentage(entry.isByPercentage() || equalByShares); //for shares for (String userId : userIds) { String share = record.get("for:" + userId); double value; if (share.contains("%")) { entry.setForPercentage(true); value = Double.parseDouble(share.replace("%", "")); value = entry.getAmount().getAmount().doubleValue() * value / 100d; } else { value = (invertSign ? -1 : 1) * Double.parseDouble(share); } entry.getForShares().put(Key.create(RegisteredUser.class, userId), BigDecimal.valueOf(value).setScale(scale, RoundingMode.DOWN)); } boolean equalForShares = checkAndBalanceZeroShares(entry.getForShares(), entry.getAmount().getAmount()); entry.setForPercentage(entry.isForPercentage() || equalForShares); OfyService.ofy().save().entity(entry).now(); createdKeys.add(Key.create(entry)); EntryOperation operation = new EntryOperation(Key.create(group), Key.create(entry), new Date(), Key.create(RegisteredUser.class, securityContext.getUserPrincipal().getName()), EntryOperation.Type.IMPORT); OfyService.ofy().save().entity(operation).now(); LOG.info(String.format("%s created.", entry)); } return createdKeys; } }); //count keys int numberOfCreatedChapters = 0; int numberOfCreatedEntries = 0; for (Key<?> key : createdKeys) { if (key.getKind().equals(Entry.class.getSimpleName())) { numberOfCreatedEntries = numberOfCreatedEntries + 1; } else if (key.getKind().equals(Chapter.class.getSimpleName())) { numberOfCreatedChapters = numberOfCreatedChapters + 1; } } return Response.ok(String.format("Done: %d chapters and %d entries created.", numberOfCreatedChapters, numberOfCreatedEntries)).build(); } catch (RuntimeException e) { LOG.warning(String.format("Unexpected %s: %s.", e.getClass().getSimpleName(), e.getMessage())); return Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(String.format("Unexpected %s: %s.", e.getClass().getSimpleName(), e.getMessage())) .build(); } }
From source file:com.mirth.connect.connectors.doc.DocumentWriter.java
private void pageSizeComboBoxActionPerformed() { if (pageSizeUpdating) { return;/* w w w .j ava 2s. co m*/ } pageSizeUpdating = true; PageSize pageSize = (PageSize) pageSizeComboBox.getSelectedItem(); if (pageSize != PageSize.CUSTOM) { pageSizeComboBox.setModel(new DefaultComboBoxModel<PageSize>( ArrayUtils.subarray(PageSize.values(), 0, PageSize.values().length - 1))); pageSizeComboBox.setSelectedItem(pageSize); pageSizeWidthField .setText(String.valueOf(new BigDecimal(pageSize.getWidth()).setScale(2, RoundingMode.DOWN))); pageSizeWidthField.setCaretPosition(0); pageSizeHeightField .setText(String.valueOf(new BigDecimal(pageSize.getHeight()).setScale(2, RoundingMode.DOWN))); pageSizeHeightField.setCaretPosition(0); pageSizeUnitComboBox.setSelectedItem(pageSize.getUnit()); } pageSizeUpdating = false; }
From source file:org.libreplan.web.orders.ManageOrderElementAdvancesModel.java
@Override public BigDecimal getPercentageAdvanceMeasurement(AdvanceMeasurement advanceMeasurement) { AdvanceAssignment assignment = advanceMeasurement.getAdvanceAssignment(); if (assignment == null) { return BigDecimal.ZERO; }//from w ww .ja v a2 s. c o m BigDecimal maxValue; if (assignment instanceof IndirectAdvanceAssignment) { maxValue = orderElement.calculateFakeDirectAdvanceAssignment((IndirectAdvanceAssignment) assignment) .getMaxValue(); } else { maxValue = ((DirectAdvanceAssignment) assignment).getMaxValue(); } if (maxValue.compareTo(BigDecimal.ZERO) <= 0) { return BigDecimal.ZERO; } BigDecimal value = advanceMeasurement.getValue(); if (value == null) { return BigDecimal.ZERO; } BigDecimal division = value.divide(maxValue.setScale(2), 4, RoundingMode.DOWN); return (division.multiply(new BigDecimal(100))).setScale(2, RoundingMode.DOWN); }
From source file:org.libreplan.web.orders.ManageOrderElementAdvancesModel.java
@Override @Transactional(readOnly = true)//w ww.ja v a2s. co m public XYModel getChartData(Set<AdvanceAssignment> selectedAdvances) { XYModel xyModel = new SimpleXYModel(); for (AdvanceAssignment each : selectedAdvances) { DirectAdvanceAssignment directAdvanceAssignment; if (each instanceof DirectAdvanceAssignment) { directAdvanceAssignment = (DirectAdvanceAssignment) each; } else { directAdvanceAssignment = calculateFakeDirectAdvanceAssignment((IndirectAdvanceAssignment) each); } if (directAdvanceAssignment != null) { String title = getInfoAdvanceAssignment(directAdvanceAssignment); SortedSet<AdvanceMeasurement> listAdvanceMeasurements = directAdvanceAssignment .getAdvanceMeasurements(); if (listAdvanceMeasurements.size() > 1) { for (AdvanceMeasurement advanceMeasurement : listAdvanceMeasurements) { BigDecimal value = advanceMeasurement.getValue(); if ((selectedAdvances.size() > 1) && (value != null) && (value.compareTo(BigDecimal.ZERO) > 0)) { BigDecimal maxValue = directAdvanceAssignment.getMaxValue(); value = value.setScale(2).divide(maxValue, RoundingMode.DOWN); } LocalDate date = advanceMeasurement.getDate(); if ((value != null) && (date != null)) { xyModel.addValue(title, date.toDateTimeAtStartOfDay().getMillis(), value); } } } } } return xyModel; }
From source file:org.jumpmind.symmetric.io.data.writer.DatabaseWriterTest.java
private String[] massageExpectectedResultsForDialect(String[] values) { RoundingMode mode = RoundingMode.DOWN; if (values[5] != null && (!(platform instanceof OracleDatabasePlatform || platform instanceof MsSql2000DatabasePlatform || platform instanceof MsSql2005DatabasePlatform || platform instanceof MsSql2008DatabasePlatform || platform instanceof AseDatabasePlatform || platform instanceof SqlAnywhereDatabasePlatform))) { values[5] = values[5].replaceFirst(" \\d\\d:\\d\\d:\\d\\d\\.?0?", " 00:00:00.0"); }//ww w . j a v a 2s . com if (values[10] != null) { values[10] = values[10].replace(',', '.'); } if (values[10] != null && !(platform instanceof OracleDatabasePlatform)) { int scale = 17; if (platform instanceof MySqlDatabasePlatform) { scale = 16; } DecimalFormat df = new DecimalFormat("0.00####################################"); values[10] = df.format(new BigDecimal(values[10]).setScale(scale, mode)); } // Adjust character fields that may have been adjusted from null to a default space with appropriate padding values[3] = translateExpectedCharString(values[3], 50, false); values[4] = translateExpectedCharString(values[4], 50, true); return values; }
From source file:jp.furplag.util.commons.NumberUtils.java
/** * to round towards zero ({@link java.math.RoundingMode#DOWN}) . * * @param o the object, number or string. * @param scale scale of fraction./*from w w w .j a va 2 s . co m*/ * @param type return type. * @return {@code ((BigDecimal) o).setScale(scale, RoundingMode.DOWN)}. */ public static <T extends Number> T down(final Object o, final Number scale, final Class<T> type) { return setScale(o, scale, RoundingMode.DOWN, type); }
From source file:org.op4j.MiscTest.java
@Test public void test() throws Exception { final StopWatch watch = new StopWatch(); watch.start();/*from ww w. j av a 2 s. c om*/ final String[] stringsArr1 = new String[] { "Hello", "Goodbye", null }; final List<String> stringsList1 = Arrays.asList(stringsArr1); final String[][] stringsStrings1 = new String[][] { new String[] { "Hello!", "Goodbye!" }, new String[] { "Hola!", "Adis!" } }; final List<String>[] stringsListStrings1 = (List<String>[]) new List<?>[] { Arrays.asList(new String[] { "Hello!", "Goodbye!" }), Arrays.asList(new String[] { "Hola!", "Adis!" }) }; final List<List<String>> stringsListStringsList1 = Arrays.asList(stringsListStrings1); final Map<String, String> map1 = new LinkedHashMap<String, String>(); map1.put("es", "Hola!"); map1.put("en", "Hello!"); map1.put("gl", "Ola!"); map1.put("ca", "Hola!"); final Map<String, String> map2 = new LinkedHashMap<String, String>(); map2.put("es", "Adis!"); map2.put("en", "Goodbye!"); map2.put("gl", "Adus!"); map2.put("ca", "Adu!"); map2.put("fr", "Adieu!"); final Map<String, String>[] maps1 = (Map<String, String>[]) new Map<?, ?>[] { map1, map2 }; System.out.println(Op.onList(stringsList1).get()); System.out.println(Op.onList(stringsList1).forEach().get()); final BigDecimal bd = new BigDecimal("3455234.6325"); final Float f = Float.valueOf(3455234.6325f); final Double d = Double.valueOf(3455234.6325); System.out.println(bd.doubleValue()); System.out.println(f); System.out.println(d); System.out.println( Op.onList(Arrays.asList(new Integer[] { 2, 3, 4, 1, 2, 2, 4, 5, 2, 3, 5, 6, 87, 45, 2, 3, 34, 1 })) .get()); System.out.println( Op.onList(Arrays.asList(new Integer[] { 2, 3, 4, 1, 2, 2, 4, 5, 2, 3, 5, 6, 87, 45, 2, 3, 34, 1 })) .distinct().get()); final List<List<String>> listOfListOfString1 = Arrays.asList((List<String>[]) new List<?>[] { Arrays.asList(new String[] { "a", "b", "a" }), Arrays.asList(new String[] { "a", "b", "a" }) }); final Set<Set<String>> setOfsetOfString1 = new LinkedHashSet<Set<String>>( Arrays.asList((Set<String>[]) new Set<?>[] { new LinkedHashSet<String>(Arrays.asList(new String[] { "a", "b", "a" })), new LinkedHashSet<String>(Arrays.asList(new String[] { "a", "b", "a" })) })); final String[][] arrayOfArrayOfString1 = new String[][] { new String[] { "a", "b", "a" }, new String[] { "a", "b", "a" } }; System.out.println(Op.onList(stringsList1).addAll("World!", "Mars!").get()); System.out.println(Op.onList(stringsList1).insertAll(1, "World!", "Mars!").get()); System.out.println(Op.onList(stringsList1).addAll(stringsList1).get()); System.out.println(Op.onList(stringsList1).get()); System.out.println(Op.onList(stringsList1).removeAllIndexes(0, 2).get()); System.out.println(Op.onList(stringsList1).removeAllIndexesNot(0).get()); System.out.println(Op.onList(stringsList1).removeAllIndexesNot(0, 2).get()); System.out.println(Op.onList(stringsList1).removeAllTrue(new IFunction<String, Boolean>() { public Boolean execute(String target, final ExecCtx ctx) { return Boolean.valueOf(target == null); } }).get()); System.out.println(Op.onList(stringsList1).removeAllNull().get()); System.out.println("================"); final Set<String> stringSet1 = new LinkedHashSet<String>(stringsList1); System.out.println(Op.onSet(stringSet1).addAll("World!", "Mars!").get()); System.out.println(Op.onSet(stringSet1).insertAll(1, "World!", "Mars!").get()); System.out.println(Op.onSet(stringSet1).addAll(stringsList1).get()); System.out.println("---"); System.out.println(Op.onSet(stringSet1).get()); System.out.println(Op.onSet(stringSet1).removeAllIndexes(0, 2).get()); System.out.println(Op.onSet(stringSet1).removeAllIndexesNot(0).get()); System.out.println(Op.onSet(stringSet1).removeAllIndexesNot(0, 2).get()); System.out.println(Op.onSet(stringSet1).removeAllNull().get()); System.out.println( printArray(Op.onArrayOf(Types.STRING, stringsArr1).insertAll(2, "lalero", "lururu").get())); System.out.println(Op.onMap(map1).put("fr", "All!").get()); System.out.println(Op.onMap(map1).insert(0, "fr", "All!").get()); System.out.println(Op.onMap(map1).insert(2, "fr", "All!").get()); System.out.println(Op.onMap(map2).get()); System.out.println(Op.onMap(map2).putAll(Op.onMap(map1).insert(0, "gl", "Meuuuu!").get()).get()); System.out.println(Op.onListFor(234, 12, 231)); System.out.println(Op.onListFor(234).addAll(10)); System.out.println(Op.onListFor(234).insert(0, 10)); System.out.println(Op.onListFor(234).addAll(10).insert(1, 3)); System.out.println(Op.onListFor(234).addAll(10).insert(1, 3).addAll((Integer) null)); System.out.println(Op.onListFor(234).addAll(10).insert(1, 3).addAll((Integer) null).removeAllNull()); System.out.println(Op.onListFor(234).addAll(10).insert(1, 3).removeAllIndexesNot(1)); System.out.println(printArray(Op.on(234).intoSingletonArrayOf(Types.INTEGER).addAll(8).get())); System.out.println(Op.on((List) null).addAll(123)); System.out.println(Op.on((Object) null).intoSingletonList().get()); System.out.println(Op.on((Object) null).intoSingletonSet().get()); System.out.println(printArray(Op.on((String) null).intoSingletonArrayOf(Types.STRING).addAll("a") .removeAllNull().removeAllIndexes(0).get())); // System.out.println(printArray(Op.buildArrayOfArray(Types.STRING).addAll(Op.buildArray(Types.STRING).addAll("a","b").get()).addAll(Op.buildArray(Types.STRING).addAll("1","2","3").get()).get())); // System.out.println(Op.buildMap(Types.INTEGER,Types.STRING).put(12,"hello!").get()); System.out.println(Op.onListFor("a", 1, "b", 3).couple().get()); System.out.println(Op.onListFor("hello", "goodbye", "adios", "ciao", "hola").sort().get()); System.out.println( Op.onListFor("hello", "goodbye", "adios", "ciao", "hola").toSet().sort(new Comparator<String>() { public int compare(String o1, String o2) { if (o1.length() < o2.length()) { return -1; } else if (o1.length() == o2.length()) { return 0; } return 1; } }).get()); System.out.println(printArray( Op.onListFor("hello", "goodbye", "adios", "ciao", "hola").toArrayOf(Types.STRING).sort().get())); System.out.println(printArray(Op.onListFor("hello", "goodbye", "adios", "ciao", "hola") .toArrayOf(Types.STRING).sort(new Comparator<String>() { public int compare(String o1, String o2) { if (o1.length() < o2.length()) { return -1; } else if (o1.length() == o2.length()) { return 0; } return 1; } }).get())); System.out.println( Op.on("12314123.4123").exec(FnString.toInteger(RoundingMode.CEILING, DecimalPoint.IS_POINT)).get()); System.out.println( Op.on("12314123.4123").exec(FnString.toInteger(RoundingMode.CEILING, DecimalPoint.IS_POINT)).get()); System.out.println(Op.on("12314123").exec(FnString.toInteger()).get()); System.out.println(Op.on("12314123").exec(FnString.toLong()).get()); System.out.println(Op.on("12314123").exec(FnString.toBigInteger()).get()); System.out.println(Op.on("12314123.4123").exec(FnString.toDouble()).get()); System.out.println(Op.on("12314123.4123").exec(FnString.toDouble(3, RoundingMode.CEILING)).get()); System.out.println(Op.on("12314123.4123").exec(FnString.toBigDecimal(3, RoundingMode.CEILING)).get()); final SimpleDateFormat dateFormat = new SimpleDateFormat(); System.out.println(dateFormat .format(Op.on(Calendar.getInstance()).exec(FnCalendar.truncate(Calendar.DATE)).get().getTime())); System.out.println(dateFormat .format(Op.on("25/nov/1979").exec(FnString.toCalendar("dd/MMM/yyyy", "es")).get().getTime())); // System.out.println(dateFormat.format(Op.onAll(1979, 11, 25, 12, 30).buildList().exec(ToCalendar.fromString("dd/MMM/yyyy", "es")).get().getTime())); System.out.println(dateFormat.format(Op.on(Op.onListFor(1979, 11, 25, 12, 30).get()) .exec(FnCalendar.fieldIntegerListToCalendar()).get().getTime())); System.out.println(dateFormat.format(Op.on(Op.onListFor("1979", "11", "25", "12", "30").get()) .toArrayOf(Types.STRING).exec(FnCalendar.fieldStringArrayToCalendar()).get().getTime())); System.out.println(Op.on(Op.onListFor(1979, 11, 25, 12, 30).get()).exec(FnList.ofInteger().sort()).get()); System.out.println(Op.on(Op.onSetFor(1979, 11, 25, 12, 30).get()).exec(FnSet.ofInteger().sort()).get()); System.out.println(Op.on(Op.onListFor(1979, 11, 25, 12, 30, 1980, 2, 43, 12, 11).get()) .exec(FnList.ofInteger().distinct()).get()); System.out.println(Op.on("hello").intoSingletonList().get()); System.out.println(printArray(Op.on("hello").intoSingletonArrayOf(Types.STRING).get())); // System.out.println(Op.buildList(Types.CALENDAR) // .addAll(Calendar.getInstance(), Calendar.getInstance()) // .forEach().exec(ToString.fromCalendar(DateStyle.FULL, TimeStyle.NONE, Locale.UK)).get()); // // System.out.println(Op.buildList(Types.CALENDAR) // .addAll(Calendar.getInstance(), Calendar.getInstance()) // .forEach().exec(ToString.fromCalendar(DateStyle.FULL, TimeStyle.SHORT, Locale.UK)).get()); // // System.out.println(Op.buildList(Types.CALENDAR) // .addAll(Calendar.getInstance(), Calendar.getInstance()) // .forEach().exec(ToString.fromCalendar("dd-MMM-yyyy", Locale.UK)).get()); // // System.out.println(Op.buildList(Types.CALENDAR) // .addAll(Calendar.getInstance(), Calendar.getInstance()) // .forEach().exec(ToString.fromCalendar("dd-MMMM-yyyy")).get()); // // System.out.println(Op.buildList(Types.DATE) // .addAll(new java.sql.Date(Calendar.getInstance().getTimeInMillis())) // .forEach().exec(ToString.fromDate("dd-MMM-yyyy", Locale.UK)).get()); // // // System.out.println(Op.buildList(Types.STRING) // .addAll(" Company ", " day ") // .forEach().exec(StringFuncs.trim()).get()); // System.out.println(Op.buildList(Types.STRING) // .addAll(" Company ", " day ") // .forEach().exec(StringFuncs.trim()).exec(StringFuncs.toUpperCase()).get()); System.out.println(Op.on("Dublin").exec(FnString.toHexadecimal(Charset.forName("ISO-8859-1"))) .exec(FnString.fromHexadecimal(Charset.forName("ISO-8859-1"))).get()); // System.out.println(Op.buildList(Types.NUMBER) // .addAll(45.9, new BigDecimal(34.456)) // .forEach().exec(ToString.fromCurrency(Locale.getDefault(), // 1, 2, 10, true)).get()); // System.out.println(Op.buildList(Types.NUMBER) // .addAll(45.9, 45, new BigDecimal(34.456)) // .forEach().exec(ToString.fromCurrency(Locale.getDefault(), // 1, 0, 0, true)).get()); // // System.out.println(Op.buildList(Types.NUMBER) // .addAll(45.9, 45, new BigDecimal(34.456), 0, 0.5, 0.211) // .forEach().exec(ToString.fromPercent(Locale.getDefault(), // 1, 0, 10, ',', '\'', false)).get()); System.out.println(Op.onArrayOf(Types.STRING, stringsArr1).toSet().get()); final List<String[]> listOfStringArray1 = new ArrayList<String[]>(); listOfStringArray1.add(Op.onListFor("Hola", "Hello", "Ciao", "Ola").toArrayOf(Types.STRING).get()); listOfStringArray1.add(Op.onListFor("Adios", "Goodbye", "Ciao", "Adus").toArrayOf(Types.STRING).get()); final List<Set<String>> listOfStringSet1 = new ArrayList<Set<String>>(); listOfStringSet1.add(Op.onListFor("Hola", "Hello", "Ciao", "Ola").toSet().get()); listOfStringSet1.add(Op.onListFor("Adios", "Goodbye", "Ciao", "Adus").toSet().get()); final Set<String[]> setOfStringArray1 = new LinkedHashSet<String[]>(); setOfStringArray1.add(Op.onListFor("Hola", "Hello", "Ciao", "Ola").toArrayOf(Types.STRING).get()); setOfStringArray1.add(Op.onListFor("Adios", "Goodbye", "Ciao", "Adus").toArrayOf(Types.STRING).get()); final Set<List<String>> setOfStringList1 = new LinkedHashSet<List<String>>(); setOfStringList1.add(Op.onArrayFor("Hola", "Hello", "Ciao", "Ola").toList().get()); setOfStringList1.add(Op.onArrayFor("Adios", "Goodbye", "Ciao", "Adus").toList().get()); final Set<Set<String>> setOfStringSet1 = new LinkedHashSet<Set<String>>(); setOfStringSet1.add(Op.onListFor("Hola", "Hello", "Ciao", "Ola").toSet().get()); setOfStringSet1.add(Op.onListFor("Adios", "Goodbye", "Ciao", "Adus").toSet().get()); System.out.println(Op.on("http://www.google.es/search?q=op4j&unusedParam=unusedValue '' 2^2 ") .exec(FnString.escapeJavaScript()).get()); System.out.println( Op.on("Body tag is written like \"<body>content here</body>\"").exec(FnString.escapeHTML()).get()); System.out.println("***___****___****"); System.out.println(Op.onList(stringsList1).forEach().ifNotNull().exec(FnString.toUpperCase()).get()); System.out.println("***___****___****"); System.out.println(Op.onList(listOfListOfString1).get()); // System.out.println(Op.onMap(map1).forEachEntry().exec(Ognl.forString("'in ' + #target.key + ' you say ' + #target.value")).get()); System.out.println(Op.onList(stringsList1).removeAllNull().sort().get()); // final List<Map<String,String>> listOfMapOfStringString1 = // Op.buildList(Types.MAP_OF_STRING_STRING).add(map1).add(map2).get(); // // System.out.println(printArray(Op.onListOfMap(listOfMapOfStringString1).toArrayOfMap().get())); System.out.println(Types.LIST_ITERATOR_OF_BOOLEAN.getSimpleName()); System.out.println(Op.onList(stringsList1).get()); System.out.println(Op.onList(stringsList1).forEach().replaceWith("op4j is great!").get()); System.out.println(Op.onList(stringsList1).forEach().replaceIfNullWith("op4j is great!").get()); System.out.println(printArray( Op.onArrayOf(Types.STRING, stringsArr1).forEach().replaceIfNullWith("op4j is great!").get())); System.out.println(printArray(Op.onArrayOf(Types.STRING, stringsArr1) .replaceWith(new String[] { "alpha", "beta" }).forEach().exec(FnString.toUpperCase()).get())); // System.out.println(Op.buildListOfList(Types.STRING).add(stringsList1).add(stringsList1).get()); // System.out.println(Op.buildListOfList(Types.STRING).addAll(stringsList1, stringsList1).get()); Op.on(Integer.valueOf(12)).exec(FnObject.intoSingletonArrayOf(Types.INTEGER)).get(); watch.stop(); System.out.println("TIME: " + watch.toString()); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); List<String> list = Arrays.asList(new String[] { "12/10/1492", "6/12/1978", "15/07/2045", null }); Set<String> set1 = new LinkedHashSet<String>(list); Set<String> set2 = Op.on(list).toSet().get(); System.out.println("set1 : " + set1); System.out.println("set2 : " + set2); Set<Calendar> set3 = Op.on(list).toSet().forEach().exec(FnString.toCalendar("dd/MM/yyyy")).get(); System.out.println("set3asStr : " + Op.on(set3).map(FnCalendar.toStr("EEEE dd MMMM yyyy")).get()); Set<Calendar> set4 = Op.on(list).toSet().removeAllNull().forEach().exec(FnString.toCalendar("dd/MM/yyyy")) .get(); System.out.println( "set4asStr : " + Op.on(set4).map(FnCalendar.toStr("EEEE dd MMMM yyyy", new Locale("en"))).get()); Set<Calendar> set5 = Op.on(list).toSet().removeAllNull().map(FnString.toCalendar("dd/MM/yyyy")).get(); System.out.println( "set5asStr : " + Op.on(set5).map(FnCalendar.toStr("EEEE dd MMMM yyyy", new Locale("en"))).get()); Calendar now = Calendar.getInstance(); Set<Calendar> set6 = Op.on(list).toSet().map(FnString.toCalendar("dd/MM/yyyy")) .removeAllNullOrTrue(FnCalendar.after(now)).get(); System.out.println("set6asStr : " + Op.on(set6).map(FnCalendar.toStr("EEEE dd MMMM yyyy HH:mm:ss", new Locale("en"))).get()); // **************************** // WARNING: Non-op4j code!! // **************************** SimpleDateFormat dateFormat1 = new SimpleDateFormat("dd/MM/yyyy"); Set<Calendar> set = new LinkedHashSet<Calendar>(); for (String element : list) { if (element != null) { Date date = null; try { date = dateFormat1.parse(element); } catch (ParseException e) { throw new RuntimeException(e); } Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(date.getTime()); if (!calendar.after(now)) { set.add(calendar); } } } System.out.println("setasStr : " + Op.on(set).map(FnCalendar.toStr("EEEE dd MMMM yyyy HH:mm:ss", new Locale("en"))).get()); Function<List<String>, Set<Calendar>> conversionFunction = Fn.onListOf(Types.STRING).toSet() .map(FnString.toCalendar("dd/MM/yyyy")).removeAllNullOrTrue(FnCalendar.after(now)).get(); System.out.println("setFnasStr : " + Op.on(conversionFunction.execute(list)) .map(FnCalendar.toStr("EEEE dd MMMM yyyy HH:mm:ss", new Locale("en"))).get()); int[] v1 = new int[] { 3, 2, 1, 3 }; long[] v2 = new long[] { 3, 2, 1, 3 }; Op.on(1).get(); List<Integer> iL = Op.onListFor(2, 1, 4, 213).get(); System.out.println(iL); System.out.println(Arrays.asList(Op.on(v1).forEach().exec(FnInteger.add(Integer.valueOf(10))).get())); Op.on(v2).forEach().get(); Op.on(123).exec(new IFunction<Integer, String>() { public String execute(Integer input, ExecCtx ctx) throws Exception { return "The input number is: " + input; } }).get(); System.out.println(Op.on(23.24).exec(FnDouble.add(43)).get()); System.out.println(Op.on(BigDecimal.valueOf(23.24)).exec(FnBigDecimal.add(1.2)).get()); System.out.println(Op.onListFor(30, 30, 40).map(FnNumber.toBigInteger()) .exec(FnBigInteger.avg(RoundingMode.CEILING)).get()); System.out.println(Op.on(10).exec(FnInteger.divideBy(3, RoundingMode.CEILING)).get()); Function<Integer, Boolean> fnAnd1 = FnBoolean.and(FnObject.eq("lala"), FnNumber.notEq(534)); System.out.println(Op.on(233).exec(FnBoolean.and(FnNumber.greaterThan(44), FnObject.lessThan(534))).get()); System.out.println( Op.on(1233).ifTrue(FnBoolean.not(FnBoolean.and(FnNumber.greaterThan(44), FnObject.lessThan(534)))) .exec(FnInteger.add(10)).get()); System.out.println(Op.on(1233).exec(FnFunc.chain(FnInteger.add(10), FnNumber.greaterThan(1200))).get()); System.out.println(Op.onListFor(1, 2, 3, 4).exec(FnList.ofInteger().containsAny(12, 3)).get()); String[] arr231 = new String[] { "be", "a", "31aa", "31_l", "31A" }; System.out.println(Arrays.asList(FnArray.ofString().sort().execute(arr231))); System.out .println(Arrays.asList(FnArray.ofString().sortBy(Call.methodForInteger("length")).execute(arr231))); System.out .println(FnList.ofString().sortBy(Call.methodForInteger("length")).execute(Arrays.asList(arr231))); String[] datesStr = new String[] { "12-10-1492", "06-12-1978" }; List<Calendar> dates = Op.on(datesStr).toList().map(FnString.toCalendar("dd-MM-yyyy")).get(); System.out.println(Op.on(dates).map(FnCalendar.toStr("yyyy, MMMM dd", new Locale("gl", "ES"))).get()); Function<Integer, Boolean> afnb1 = new Function<Integer, Boolean>() { public Boolean execute(Integer input, ExecCtx ctx) throws Exception { return Boolean.TRUE; } }; Function<Number, Boolean> afnb2 = new Function<Number, Boolean>() { public Boolean execute(Number input, ExecCtx ctx) throws Exception { return Boolean.TRUE; } }; Function<Integer, Boolean> afnb = FnBoolean.and(afnb1, afnb2); Function<Number, Boolean> bfnb1 = new Function<Number, Boolean>() { public Boolean execute(Number input, ExecCtx ctx) throws Exception { return Boolean.TRUE; } }; Function<Integer, Boolean> bfnb2 = new Function<Integer, Boolean>() { public Boolean execute(Integer input, ExecCtx ctx) throws Exception { return Boolean.TRUE; } }; Function<Integer, Boolean> bfnb = FnBoolean.and(bfnb1, bfnb2); Op.on(231).ifTrue(afnb).get(); Op.on(231).ifTrue(bfnb).get(); Op.on(231).ifTrue(FnBoolean.and(afnb1, afnb2)).get(); Op.on(231).ifTrue(FnBoolean.and(bfnb1, bfnb2)).get(); Function<Object, Boolean> cfnb1 = new Function<Object, Boolean>() { public Boolean execute(Object input, ExecCtx ctx) throws Exception { return Boolean.TRUE; } }; Function<Number, Boolean> cfnb2 = new Function<Number, Boolean>() { public Boolean execute(Number input, ExecCtx ctx) throws Exception { return Boolean.TRUE; } }; Function<Number, Boolean> cfnb = FnBoolean.and(cfnb1, cfnb2); Function<Number, Boolean> dfnb1 = new Function<Number, Boolean>() { public Boolean execute(Number input, ExecCtx ctx) throws Exception { return Boolean.TRUE; } }; Function<Object, Boolean> dfnb2 = new Function<Object, Boolean>() { public Boolean execute(Object input, ExecCtx ctx) throws Exception { return Boolean.TRUE; } }; Function<Number, Boolean> dfnb = FnBoolean.and(dfnb1, dfnb2); Op.on(231.2).ifTrue(cfnb).get(); Op.on(231.1).ifTrue(dfnb).get(); Op.on(231.2).ifTrue(FnBoolean.and(cfnb1, cfnb2)).get(); Op.on(231.1).ifTrue(FnBoolean.and(dfnb1, dfnb2)).get(); Function<Number, Integer> fnz1 = new Function<Number, Integer>() { public Integer execute(Number input, ExecCtx ctx) throws Exception { // TODO Auto-generated method stub return null; } }; Function<Integer, Integer> fnn1 = FnFunc.ifTrueThen(Types.INTEGER, FnNumber.greaterThan(2), fnz1); Fn.on(Types.INTEGER).exec(FnFunc.ifTrueThen(Types.NUMBER, FnNumber.greaterThan(2), fnz1)).get(); BigInteger biValue = BigInteger.valueOf(-1256565646); System.out.println("Starting value = " + biValue); BigInteger biOpResult = Op.on(biValue).exec(FnBigInteger.divideBy(BigInteger.valueOf(23))) .exec(FnBigInteger.pow(3)).exec(FnBigInteger.subtract(BigInteger.valueOf(5))) .exec(FnBigInteger.abs()).get(); System.out.println("With op4j: " + biOpResult); BigInteger biNorResult = biValue.divide(BigInteger.valueOf(23)).pow(3).subtract(BigInteger.valueOf(5)) .abs(); System.out.println("Without op4j: " + biNorResult); BigInteger biOpResult1 = Op.on(biValue).exec(FnBigInteger.divideBy(BigInteger.valueOf(23))).get(); System.out.println("[1] With op4j: " + biOpResult1); BigInteger biNorResult1 = biValue.divide(BigInteger.valueOf(23)); System.out.println("[1] Without op4j: " + biNorResult1); BigDecimal biOpResult1d = Op.on(new BigDecimal(biValue)) .exec(FnBigDecimal.divideBy(BigDecimal.valueOf(23.0), RoundingMode.DOWN)).get(); System.out.println("[1D] With op4j: " + biOpResult1d); BigDecimal biNorResult1d = new BigDecimal(biValue).divide(BigDecimal.valueOf(23.0), RoundingMode.DOWN); System.out.println("[1D] Without op4j: " + biNorResult1d); System.out .println( Op.on(Types.STRING, null) .exec(FnFunc.ifTrueThen(Types.STRING, FnBoolean.or(FnObject.isNull(), FnBoolean.and(FnObject.isNotNull(), FnFunc.chain(FnString.toInteger(), FnNumber.greaterThan(100)))), FnObject.replaceWith("lelo"))) .get()); System.out.println(Arrays.asList(Op.onArrayFor(4, 2).get())); System.out.println(Op.on("hello").zipKey(98).get()); System.out.println(Op.onListFor("en", "en", "es", "gl", "fr") .zipAndGroupValues("hello", "goodbye", "hola", "ola", "all").get()); System.out.println(Op.onListFor("hello", "goodbye", "hola", "ola", "all") .zipAndGroupKeys("en", "en", "es", "gl", "fr").get()); System.out.println(Op.onArrayFor("hello", "goodbye", "hola", "ola", "all") .zipAndGroupKeys("en", "en", "es", "gl", "fr").get()); System.out.println(Op.onMapFor(23, "twenty-three").and(43, "forty-three").and(10, "ten").sort().get()); System.out.println(Arrays.asList(Op.onArrayFor(1, 2, 1, 2, 2) .zipAndGroupValues(Types.STRING, "a", "b", "c", "d", "e").get().get(1))); System.out.println( Op.on("hello").ifTrue(FnString.notEq("uncapitalizable")).exec(FnString.toUpperCase()).get()); System.out.println(Op.on("uncapitalizable").ifTrue(FnString.notEq("uncapitalizable")) .exec(FnString.toUpperCase()).get()); Map<String, Integer> agesByName = Op.onListFor(27, 49, 19).zipKeys("John", "Mary", "Derek").get(); System.out.println(agesByName); Map<String, String> capitals = Op .onListFor("Spain", "Madrid", "United Kingdom", "London", "France", "Paris").couple().get(); System.out.println(capitals); String date = "06/12/1978"; Calendar cal = Op.on(date).exec(FnString.toCalendar("dd/MM/yyyy")).get(); System.out.println(dateFormat.format(cal.getTime())); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Date dt = sdf.parse("06/12/1978"); Calendar c = Calendar.getInstance(); c.setTime(dt); System.out.println(dateFormat.format(c.getTime())); System.out.println(Op.onListFor(2, 12, 42, 5, 9, 24) .mapIfTrue(FnNumber.lessOrEqTo(10), FnObject.replaceWith("<"), FnObject.replaceWith(">")).get()); System.out.println(Op.on("LO E I N OR! ae").exec(FnString.asciify()).get()); System.out.println(Op.on(" a nu NU nu NU ").exec(FnString.asciify()).get()); System.out.println(Op.on("").exec(FnString.asciify()).get()); Pair<Integer, Integer> p = Op.on(dt).exec(FnTuple.pairWith(Call.i("getYear"), Get.i("month"))).get(); System.out.println(p); Integer i10 = Op.on(dt).exec(FnTuple.pairWith(Call.i("getYear"), Get.i("month"))) .exec(FnTuple.getValue1Of(Types.INTEGER)).get(); System.out.println(i10); }
From source file:jp.furplag.util.commons.NumberUtilsTest.java
/** * {@link jp.furplag.util.commons.NumberUtils#divide(java.lang.Object, java.lang.Number, java.lang.Number, java.math.RoundingMode, java.lang.Class)}. *///from w ww .j av a 2 s. c o m @SuppressWarnings("unchecked") @Test public void testDivideTNumberNumberRoundingModeClassOfT() { assertEquals("null", null, divide(null, null, null, null, null)); assertEquals("null", null, divide(10, 5, 0, null, null)); assertEquals("null", null, divide(10, 5, null, null, null)); assertEquals("null", null, divide(10, 3, 2, RoundingMode.DOWN, null)); assertEquals("null", (Object) 3.33f, divide(10, 3, 2, RoundingMode.DOWN, float.class)); try { for (Class<?> type : PRIMITIVES) { Object expected = ClassUtils.primitiveToWrapper(type).getMethod("valueOf", String.class) .invoke(null, "0"); assertEquals("fallback: " + type.getSimpleName(), expected, divide(null, null, null, null, (Class<? extends Number>) type)); } for (Class<?> type : NUMBERS) { Object expected = valueOf(3.33, (Class<? extends Number>) type); assertEquals("10 / 3: " + type.getSimpleName(), expected, divide(10, 3, 2, RoundingMode.DOWN, (Class<? extends Number>) type)); assertEquals("10 / 3: " + type.getSimpleName(), expected, divide(10, 3, 2, RoundingMode.HALF_EVEN, (Class<? extends Number>) type)); assertEquals("10 / 3: " + type.getSimpleName(), expected, divide(10, 3, 2, RoundingMode.HALF_UP, (Class<? extends Number>) type)); assertEquals("10 / 3: " + type.getSimpleName(), expected, divide(10, 3, 2, RoundingMode.FLOOR, (Class<? extends Number>) type)); expected = valueOf(3.34, (Class<? extends Number>) type); assertEquals("10 / 3: " + type.getSimpleName(), expected, divide(10, 3, 2, RoundingMode.UP, (Class<? extends Number>) type)); assertEquals("10 / 3: " + type.getSimpleName(), expected, divide(10, 3, 2, RoundingMode.CEILING, (Class<? extends Number>) type)); } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace())); } }