下面列出了java.text.NumberFormat#setMinimumFractionDigits ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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());
}
/**
* 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;
}
@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};
}
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";
}
}
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);
}
}
/**
* 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));
}
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);
}
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;
}
private static NumberFormat initNF() {
NumberFormat f = NumberFormat.getInstance();
f.setMinimumIntegerDigits(1);
f.setMinimumFractionDigits(1);
f.setMaximumFractionDigits(4);
return f;
}
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};
}
@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;
}
/**
* 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));
}
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);
}
}
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;
}
/**
* 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);
}
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 );
}
/**
* 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);
}
public static String formatNumber(float number) {
NumberFormat defaultFormat = NumberFormat.getNumberInstance();
defaultFormat.setMinimumFractionDigits(1);
return defaultFormat.format(number);
}
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();
}
}
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();
}
}