Java Code Examples for java.text.NumberFormat#setMinimumFractionDigits()
The following examples show how to use
java.text.NumberFormat#setMinimumFractionDigits() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FillingLabel.java From dsworkbench with Apache License 2.0 | 6 votes |
public void setData(double[] fillings, double capacity) { this.fillings = fillings; NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(1); nf.setMaximumFractionDigits(1); double res = 0; for (Double v : fillings) { res += v * capacity; } res /= 1000; if(res > 0) { text = nf.format(res) + " K"; } else { text = "keine"; } }
Example 2
Source File: DoubleFormatTest.java From swage with Apache License 2.0 | 6 votes |
private void test(double val) throws Exception { // Should behave exactly the same as standard number format // with no extra trailing zeros, six max trailing zeros. NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMinimumFractionDigits(0); nf.setMaximumFractionDigits(6); nf.setGroupingUsed(false); String expected = nf.format(val); StringBuilder sb = new StringBuilder(); DoubleFormat.format(sb, val); assertEquals(expected, sb.toString()); }
Example 3
Source File: TtsSpan.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
/** * Convenience method takes a double and a maximum number of fractional * digits, it sets the {@link #ARG_INTEGER_PART} and * {@link #ARG_FRACTIONAL_PART} arguments. * @param number The number to be synthesized. * @param minimumFractionDigits The minimum number of fraction digits * that are pronounced. * @param maximumFractionDigits The maximum number of fraction digits * that are pronounced. If maximumFractionDigits < * minimumFractionDigits then minimumFractionDigits will be assumed * to be equal to maximumFractionDigits. * @return This instance. */ public DecimalBuilder setArgumentsFromDouble( double number, int minimumFractionDigits, int maximumFractionDigits) { // Format double. NumberFormat formatter = NumberFormat.getInstance(Locale.US); formatter.setMinimumFractionDigits(maximumFractionDigits); formatter.setMaximumFractionDigits(maximumFractionDigits); formatter.setGroupingUsed(false); String str = formatter.format(number); // Split at decimal point. int i = str.indexOf('.'); if (i >= 0) { setIntegerPart(str.substring(0, i)); setFractionalPart(str.substring(i + 1)); } else { setIntegerPart(str); } return this; }
Example 4
Source File: OverallStatResult.java From dsworkbench with Apache License 2.0 | 6 votes |
@Override public String[] getReplacements(boolean pExtended) { SimpleDateFormat df = new SimpleDateFormat("dd.MM.yy HH:mm"); NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(0); nf.setMinimumFractionDigits(0); String valStartDate = df.format(startDate); String valEndData = df.format(endDate); String valReportCount = nf.format(reportCount); String valAttackTribes = nf.format(attackers); String valAttackAllies = nf.format(attackerAllies); String valDefendTribes = nf.format(defenders); String valDefendAllies = nf.format(defenderAllies); String valKills = nf.format(kills); String valKillsAsFarm = nf.format(killsAsFarm); String valLosses = nf.format(losses); String valLossesAsFarm = nf.format(lossesAsFarm); String valLossesPerAttacker = nf.format(losses / attackers); String valLossesPerDefender = nf.format(kills / defenders); String valWallDestruction = nf.format(wallDestruction); String valBuildingDestruction = nf.format(buildingDestruction); return new String[]{valStartDate, valEndData, valReportCount, valAttackTribes, valAttackAllies, valDefendTribes, valDefendAllies, valKills, valKillsAsFarm, valLosses, valLossesAsFarm, valLossesPerAttacker, valLossesPerDefender, valWallDestruction, valBuildingDestruction}; }
Example 5
Source File: RelativeDateFormatTest.java From ccu-historian with GNU General Public License v3.0 | 5 votes |
/** * Confirm that cloning works. */ public void testCloning() { NumberFormat nf = new DecimalFormat("0"); RelativeDateFormat df1 = new RelativeDateFormat(); df1.setSecondFormatter(nf); RelativeDateFormat df2 = null; df2 = (RelativeDateFormat) df1.clone(); assertTrue(df1 != df2); assertTrue(df1.getClass() == df2.getClass()); assertTrue(df1.equals(df2)); // is the clone independent nf.setMinimumFractionDigits(2); assertFalse(df1.equals(df2)); }
Example 6
Source File: LSCurrencyFormat.java From openbd-core with GNU General Public License v3.0 | 5 votes |
public cfData execute( cfSession _session, List<cfData> parameters )throws cfmRunTimeException{ double number; String type; String returnString = ""; NumberFormat numFormat = NumberFormat.getCurrencyInstance( _session.getLocale() ); int localeMinDecDigits = numFormat.getMinimumFractionDigits(); int localeMaxDecDigits = numFormat.getMaximumFractionDigits(); if ( parameters.size() == 2 ){ number = getDoubleWithChecks( _session, parameters.get(1) ); type = parameters.get(0).getString(); } else { number = getDoubleWithChecks( _session, parameters.get(0) ); type = "local"; } if( type.equalsIgnoreCase( "local" ) ){ returnString = numFormat.format(number); } else if( type.equalsIgnoreCase( "none" ) ){ numFormat = NumberFormat.getInstance( _session.getLocale() ); numFormat.setMinimumFractionDigits( localeMinDecDigits ); numFormat.setMaximumFractionDigits( localeMaxDecDigits ); Localization.updateNoneCurrencyFormat( _session.getLocale(), numFormat ); returnString = numFormat.format(number); } else if( type.equalsIgnoreCase( "international" ) ){ numFormat = NumberFormat.getInstance( _session.getLocale() ); numFormat.setMinimumFractionDigits( localeMinDecDigits ); numFormat.setMaximumFractionDigits( localeMaxDecDigits ); returnString = new DecimalFormatSymbols( _session.getLocale() ).getInternationalCurrencySymbol() + numFormat.format(number); } else throwException( _session, " invalid type: "+type+" in LSCurrencyFormat" ); return new cfStringData( returnString ); }
Example 7
Source File: DoubleFormatTest.java From swage with Apache License 2.0 | 5 votes |
/** * This test runs a comparision of the performance of various string * formatting methods and validates that DoubleFormat is the fastest. * Not a replacement for in-depth analysis. * * If this test is failing, either DoubleFormat has a performance * regression or the built-in methods have improved enough to reconsider. * * The test can take multiple seconds to run. */ @Test public void benchmark() throws Exception { final long iterations = 1000000; long duration_StringFormat = run_benchmark(iterations, (a) -> String.format("%.6f", a)); NumberFormat javaFormatter = NumberFormat.getInstance(); javaFormatter.setMinimumFractionDigits(0); javaFormatter.setMaximumFractionDigits(6); javaFormatter.setGroupingUsed(false); long duration_JavaFormat = run_benchmark(iterations, (a) -> javaFormatter.format(a)); long duration_JavaStringBuilder = run_benchmark(iterations, (a) -> (new StringBuilder()).append(a)); long duration_DoubleFormat = run_benchmark(iterations, (a) -> DoubleFormat.format(new StringBuilder(), a)); System.out.println("DoubleFormat Performance comparison: " + iterations +" iterations"); System.out.println("\tJava String.format: " + duration_StringFormat + " ms"); System.out.println("\tJava NumberFormat: " + duration_JavaFormat + " ms"); System.out.println("\tJava StringBuilder: " + duration_JavaStringBuilder + " ms"); System.out.println("\tDoubleFormat: " + duration_DoubleFormat + " ms"); assertTrue(duration_DoubleFormat < duration_StringFormat); assertTrue(duration_DoubleFormat < duration_JavaFormat); assertTrue(duration_DoubleFormat < duration_JavaStringBuilder); }
Example 8
Source File: TDevice.java From android-project-wo2b with Apache License 2.0 | 5 votes |
public static String percent(double p1, double p2) { String str; double p3 = p1 / p2; NumberFormat nf = NumberFormat.getPercentInstance(); nf.setMinimumFractionDigits(2); str = nf.format(p3); return str; }
Example 9
Source File: DSWorkbenchStatsFrame.java From dsworkbench with Apache License 2.0 | 5 votes |
private void setupChart(String pInitialId, XYDataset pInitialDataset) { chart = ChartFactory.createTimeSeriesChart( "Spielerstatistiken", // title "Zeiten", // x-axis label pInitialId, // y-axis label pInitialDataset, // data jShowLegend.isSelected(), // create legend? true, // generate tooltips? false // generate URLs? ); chart.setBackgroundPaint(Constants.DS_BACK); XYPlot plot = (XYPlot) chart.getPlot(); setupPlotDrawing(plot); XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(); for (int i = 0; i < plot.getSeriesCount(); i++) { renderer.setSeriesLinesVisible(i, jShowLines.isSelected()); renderer.setSeriesShapesVisible(i, jShowDataPoints.isSelected()); plot.setRenderer(i, renderer); } renderer.setDefaultItemLabelsVisible(jShowItemValues.isSelected()); renderer.setDefaultItemLabelGenerator(new org.jfree.chart.labels.StandardXYItemLabelGenerator()); renderer.setDefaultToolTipGenerator(new StandardXYToolTipGenerator(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT, new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"), NumberFormat.getInstance())); int lastDataset = plot.getDatasetCount() - 1; if (lastDataset > 0) { plot.getRangeAxis().setAxisLinePaint(plot.getLegendItems().get(lastDataset).getLinePaint()); plot.getRangeAxis().setLabelPaint(plot.getLegendItems().get(lastDataset).getLinePaint()); plot.getRangeAxis().setTickLabelPaint(plot.getLegendItems().get(lastDataset).getLinePaint()); plot.getRangeAxis().setTickMarkPaint(plot.getLegendItems().get(lastDataset).getLinePaint()); } NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(0); nf.setMaximumFractionDigits(0); NumberAxis na = ((NumberAxis) plot.getRangeAxis()); if (na != null) { na.setNumberFormatOverride(nf); } }
Example 10
Source File: ScrubberProcessImpl.java From kfs with GNU Affero General Public License v3.0 | 5 votes |
/** * Generate the flag for the end of specific descriptions. This will be used in the demerger step */ protected void setOffsetString() { NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(0); nf.setMaximumIntegerDigits(2); nf.setMinimumFractionDigits(0); nf.setMinimumIntegerDigits(2); offsetString = COST_SHARE_TRANSFER_ENTRY_IND + nf.format(runCal.get(Calendar.MONTH) + 1) + nf.format(runCal.get(Calendar.DAY_OF_MONTH)); }
Example 11
Source File: BarbarianAlly.java From dsworkbench with Apache License 2.0 | 5 votes |
@Override public String getToolTipText() { NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(0); nf.setMaximumFractionDigits(0); String res = "<html><table style='border: solid 1px black; cellspacing:0px;cellpadding: 0px;background-color:#EFEBDF;'>"; res += "<tr><td><b>Stamm:</b> </td><td>" + toString() + "</td></tr>"; res += "</table></html>"; return res; }
Example 12
Source File: KillStatsFormatter.java From dsworkbench with Apache License 2.0 | 5 votes |
private String[] getStatSpecificReplacements(Stats pStats) { NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(0); nf.setMaximumFractionDigits(0); String tribe = pStats.getParent().getTribe().toBBCode(); String killsBefore = nf.format(pStats.getBashOffStart()); String killsAfter = nf.format(pStats.getBashOffEnd()); String killsDiff = nf.format(pStats.getBashOffDiff()); if (pStats.getBashOffDiff() > 0) { killsDiff = "[color=green]" + killsDiff + "[/color]"; } else { killsDiff = "[color=red]" + killsDiff + "[/color]"; } long pBefore = pStats.getBashOffStart(); double perc = 0; if (pBefore > 0) { perc = (double) 100 * (double) pStats.getBashOffDiff() / (double) pBefore; } String percentDiff = ((perc >= 0) ? "+" : "") + nf.format(perc) + "%"; if (perc > 0) { percentDiff = "[color=green]" + percentDiff + "[/color]"; } else { percentDiff = "[color=red]" + percentDiff + "[/color]"; } return new String[] {tribe, killsBefore, killsAfter, killsDiff, percentDiff}; }
Example 13
Source File: EPsScorer.java From openccg with GNU Lesser General Public License v2.1 | 5 votes |
private static NumberFormat initNF() { NumberFormat f = NumberFormat.getInstance(); f.setMinimumIntegerDigits(1); f.setMinimumFractionDigits(1); f.setMaximumFractionDigits(4); return f; }
Example 14
Source File: Main.java From currency with GNU General Public License v3.0 | 5 votes |
private boolean onCopyClick() { ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); NumberFormat numberFormat = NumberFormat.getInstance(); numberFormat.setMinimumFractionDigits(digits); numberFormat.setMaximumFractionDigits(digits); // Copy value to clip String clip = null; for (int i : selectList) { try { numberFormat.setGroupingUsed(true); Number number = numberFormat.parse(valueList.get(i)); Double value = number.doubleValue(); // Remove grouping from value numberFormat.setGroupingUsed(false); clip = numberFormat.format(value); } catch (Exception e) { } } // Copy clip to clipboard clipboard.setPrimaryClip(ClipData.newPlainText("Currency", clip)); // Clear selection selectList.clear(); adapter.notifyDataSetChanged(); // Restore menu mode = DISPLAY_MODE; invalidateOptionsMenu(); return true; }
Example 15
Source File: KStarTreeNode.java From OSPREY3 with GNU General Public License v2.0 | 5 votes |
private static String format(BigDecimal x) { NumberFormat formatter = new DecimalFormat("0.0E0"); formatter.setRoundingMode(RoundingMode.HALF_UP); formatter.setMinimumFractionDigits((x.scale() > 0) ? x.precision() : x.scale()); return formatter.format(x); }
Example 16
Source File: HiCRulerPanel.java From Juicebox with MIT License | 5 votes |
private static String formatNumber(double position) { if (showOnlyEndPts) { //Export Version NumberFormat df = NumberFormat.getInstance(); df.setMinimumFractionDigits(2); df.setMaximumFractionDigits(2); df.setRoundingMode(RoundingMode.DOWN); //return f.valueToString(position); return df.format(position); } else { DecimalFormat formatter = new DecimalFormat(); return formatter.format((int) position); } }
Example 17
Source File: StringHelper.java From batteryhub with Apache License 2.0 | 4 votes |
public static String formatNumber(float number) { NumberFormat defaultFormat = NumberFormat.getNumberInstance(); defaultFormat.setMinimumFractionDigits(1); return defaultFormat.format(number); }
Example 18
Source File: CurrencyFormat.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
static void testFormatting() { boolean failed = false; Locale[] locales = { Locale.US, Locale.JAPAN, Locale.GERMANY, Locale.ITALY, new Locale("it", "IT", "EURO") }; Currency[] currencies = { null, Currency.getInstance("USD"), Currency.getInstance("JPY"), Currency.getInstance("DEM"), Currency.getInstance("EUR"), }; String[][] expecteds = { {"$1,234.56", "$1,234.56", "JPY1,235", "DEM1,234.56", "EUR1,234.56"}, {"\uFFE51,235", "USD1,234.56", "\uFFE51,235", "DEM1,234.56", "EUR1,234.56"}, {"1.234,56 \u20AC", "1.234,56 USD", "1.235 JPY", "1.234,56 DM", "1.234,56 \u20AC"}, {"\u20AC 1.234,56", "USD 1.234,56", "JPY 1.235", "DEM 1.234,56", "\u20AC 1.234,56"}, {"\u20AC 1.234,56", "USD 1.234,56", "JPY 1.235", "DEM 1.234,56", "\u20AC 1.234,56"}, }; for (int i = 0; i < locales.length; i++) { Locale locale = locales[i]; NumberFormat format = NumberFormat.getCurrencyInstance(locale); for (int j = 0; j < currencies.length; j++) { Currency currency = currencies[j]; String expected = expecteds[i][j]; if (currency != null) { format.setCurrency(currency); int digits = currency.getDefaultFractionDigits(); format.setMinimumFractionDigits(digits); format.setMaximumFractionDigits(digits); } String result = format.format(1234.56); if (!result.equals(expected)) { failed = true; System.out.println("FAIL: Locale " + locale + (currency == null ? ", default currency" : (", currency: " + currency)) + ", expected: " + expected + ", actual: " + result); } } } if (failed) { throw new RuntimeException(); } }
Example 19
Source File: DisplayFormatters.java From BiglyBT with GNU General Public License v2.0 | 4 votes |
/** * Format a real number * * @param value real number to format * @param precision max # of digits after the decimal place * @param bTruncateZeros remove any trailing zeros after decimal place * @param bRound Whether the number will be rounded to the precision, or * truncated off. * @return formatted string */ public static String formatDecimal( double value, int precision, boolean bTruncateZeros, boolean bRound) { if (Double.isNaN(value) || Double.isInfinite(value)) { return Constants.INFINITY_STRING; } double tValue; if (bRound) { tValue = value; } else { // NumberFormat rounds, so truncate at precision if (precision == 0) { tValue = (long) value; } else { double shift = Math.pow(10, precision); tValue = ((long) (value * shift)) / shift; } } int cache_index = (precision << 2) + ((bTruncateZeros ? 1 : 0) << 1) + (bRound ? 1 : 0); NumberFormat nf = null; if (cache_index < cached_number_formats.length) { nf = cached_number_formats[cache_index]; } if (nf == null) { nf = NumberFormat.getNumberInstance(); nf.setGroupingUsed(false); // no commas if (!bTruncateZeros) { nf.setMinimumFractionDigits(precision); } if (bRound) { nf.setMaximumFractionDigits(precision); } if (cache_index < cached_number_formats.length) { cached_number_formats[cache_index] = nf; } } return nf.format(tValue); }
Example 20
Source File: CurrencyFormat.java From jdk8u_jdk with GNU General Public License v2.0 | 4 votes |
static void testFormatting() { boolean failed = false; Locale[] locales = { Locale.US, Locale.JAPAN, Locale.GERMANY, Locale.ITALY, new Locale("it", "IT", "EURO") }; Currency[] currencies = { null, Currency.getInstance("USD"), Currency.getInstance("JPY"), Currency.getInstance("DEM"), Currency.getInstance("EUR"), }; String[][] expecteds = { {"$1,234.56", "$1,234.56", "JPY1,235", "DEM1,234.56", "EUR1,234.56"}, {"\uFFE51,235", "USD1,234.56", "\uFFE51,235", "DEM1,234.56", "EUR1,234.56"}, {"1.234,56 \u20AC", "1.234,56 USD", "1.235 JPY", "1.234,56 DM", "1.234,56 \u20AC"}, {"\u20AC 1.234,56", "USD 1.234,56", "JPY 1.235", "DEM 1.234,56", "\u20AC 1.234,56"}, {"\u20AC 1.234,56", "USD 1.234,56", "JPY 1.235", "DEM 1.234,56", "\u20AC 1.234,56"}, }; for (int i = 0; i < locales.length; i++) { Locale locale = locales[i]; NumberFormat format = NumberFormat.getCurrencyInstance(locale); for (int j = 0; j < currencies.length; j++) { Currency currency = currencies[j]; String expected = expecteds[i][j]; if (currency != null) { format.setCurrency(currency); int digits = currency.getDefaultFractionDigits(); format.setMinimumFractionDigits(digits); format.setMaximumFractionDigits(digits); } String result = format.format(1234.56); if (!result.equals(expected)) { failed = true; System.out.println("FAIL: Locale " + locale + (currency == null ? ", default currency" : (", currency: " + currency)) + ", expected: " + expected + ", actual: " + result); } } } if (failed) { throw new RuntimeException(); } }