下面列出了java.text.DecimalFormat#toPattern ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* <p>Parse the value with the specified <code>Format</code>.</p>
*
* <p>This implementation is lenient whether the currency symbol
* is present or not. The default <code>NumberFormat</code>
* behaviour is for the parsing to "fail" if the currency
* symbol is missing. This method re-parses with a format
* without the currency symbol if it fails initially.</p>
*
* @param value The value to be parsed.
* @param formatter The Format to parse the value with.
* @return The parsed value if valid or <code>null</code> if invalid.
*/
@Override
protected Object parse(String value, Format formatter) {
// Initial parse of the value
Object parsedValue = super.parse(value, formatter);
if (parsedValue != null || !(formatter instanceof DecimalFormat)) {
return parsedValue;
}
// Re-parse using a pattern without the currency symbol
DecimalFormat decimalFormat = (DecimalFormat)formatter;
String pattern = decimalFormat.toPattern();
if (pattern.indexOf(CURRENCY_SYMBOL) >= 0) {
StringBuilder buffer = new StringBuilder(pattern.length());
for (int i = 0; i < pattern.length(); i++) {
if (pattern.charAt(i) != CURRENCY_SYMBOL) {
buffer.append(pattern.charAt(i));
}
}
decimalFormat.applyPattern(buffer.toString());
parsedValue = super.parse(value, decimalFormat);
}
return parsedValue;
}
/**
* Formats the given value with the given format, using scientific notation if needed.
* This is a workaround for {@link DecimalFormat} not switching automatically to scientific notation for large numbers.
*
* @param format the format to use for formatting the given value.
* @param value the value to format.
* @param action the method to invoke. Typically {@code Format::format}.
* @return the result of {@code action}.
*/
@Workaround(library="JDK", version="10")
public static String useScientificNotationIfNeeded(final Format format, final Object value, final BiFunction<Format,Object,String> action) {
if (value instanceof Number) {
final double m = abs(((Number) value).doubleValue());
if (m > 0 && (m >= 1E+9 || m < 1E-4) && format instanceof DecimalFormat) {
final DecimalFormat df = (DecimalFormat) format;
final String pattern = df.toPattern();
df.applyPattern("0.######E00");
try {
return action.apply(format, value);
} finally {
df.applyPattern(pattern);
}
}
}
return action.apply(format, value);
}
/***
* If user does not provide a valid locale it throws IllegalArgumentException.
*
* If throws an IllegalArgumentException the locale sets to default locale
*/
private void initSettings() {
boolean success = false;
while (!success) {
try {
if (fractionDigit == 0) {
fractionDigit = Currency.getInstance(locale).getDefaultFractionDigits();
}
DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
if (mGroupDivider > 0)
symbols.setGroupingSeparator(mGroupDivider);
groupDivider = symbols.getGroupingSeparator();
if (mMonetaryDivider > 0)
symbols.setMonetaryDecimalSeparator(mMonetaryDivider);
monetaryDivider = symbols.getMonetaryDecimalSeparator();
currencySymbol = symbols.getCurrencySymbol();
DecimalFormat df = (DecimalFormat) DecimalFormat.getCurrencyInstance(locale);
numberFormat = new DecimalFormat(df.toPattern(), symbols);
if (mDecimalPoints > 0) {
numberFormat.setMinimumFractionDigits(mDecimalPoints);
}
success = true;
} catch (IllegalArgumentException e) {
Log.e(getClass().getCanonicalName(), e.getMessage());
locale = getDefaultLocale();
}
}
}
@Override
public void saveValueToXML(@Nonnull Element xmlElement) {
DecimalFormat format = getValue();
if (format == null)
return;
String pattern = format.toPattern();
xmlElement.setTextContent(pattern);
}
public void test_applyPattern_icu2GroupingSizes() {
DecimalFormat decFormat = new DecimalFormat("#.#");
String[] patterns = {
"####.##", "######.######", "000000.000000",
"######.000000", "000000.######", " ###.###", "$#####.######",
"$$####.######", "%#,##,###,####", "#,##0.00;(#,##0.00)",
"##.##-E"
};
String[] expResult = {
"#0.##", "#0.######", "#000000.000000",
"#.000000", "#000000.######", " #0.###", "$#0.######",
"$$#0.######",
"%#,###,####", // icu only. icu supports two grouping sizes
"#,##0.00;(#,##0.00)",
"#0.##-E"
// icu only. E in the suffix does not need to be quoted.
};
for (int i = 0; i < patterns.length; i++) {
decFormat.applyPattern(patterns[i]);
String result = decFormat.toPattern();
assertEquals("Failed to apply following pattern: " + patterns[i] +
"\n expected: " + expResult[i] +
"\n returned: " + result, expResult[i], result);
}
}
public static String format(final long number, final String conversionPattern) {
DecimalFormat df = DECIMAL_FORMAT.get();
String previous = df.toPattern();
if (conversionPattern != null) {
df.applyPattern(conversionPattern);
}
String formatted = df.format(number);
df.applyPattern(previous);
return formatted;
}
public static String format(final double number, final String conversionPattern) {
DecimalFormat df = DECIMAL_FORMAT.get();
String previous = df.toPattern();
if (conversionPattern != null) {
df.applyPattern(conversionPattern);
}
String formatted = df.format(number);
df.applyPattern(previous);
return formatted;
}
/**
* Constructs a parser using the specified set of symbols.
*
* @param symbols the set of symbols to use.
* @param fragments reference to the {@link WKTFormat#fragments} map, or an empty map if none.
* @param numberFormat the number format provided by {@link WKTFormat}, or {@code null} for a default format.
* @param dateFormat the date format provided by {@link WKTFormat}, or {@code null} for a default format.
* @param unitFormat the unit format provided by {@link WKTFormat}, or {@code null} for a default format.
* @param errorLocale the locale for error messages (not for parsing), or {@code null} for the system default.
*/
AbstractParser(final Symbols symbols, final Map<String,Element> fragments, NumberFormat numberFormat,
final DateFormat dateFormat, final UnitFormat unitFormat, final Locale errorLocale)
{
ensureNonNull("symbols", symbols);
if (numberFormat == null) {
numberFormat = symbols.createNumberFormat();
}
this.symbols = symbols;
this.fragments = fragments;
this.dateFormat = dateFormat;
this.unitFormat = unitFormat;
this.errorLocale = errorLocale;
if (Symbols.SCIENTIFIC_NOTATION && numberFormat instanceof DecimalFormat) {
final DecimalFormat decimalFormat = (DecimalFormat) numberFormat.clone();
exponentSymbol = decimalFormat.getDecimalFormatSymbols().getExponentSeparator();
String pattern = decimalFormat.toPattern();
if (!pattern.contains("E0")) {
final StringBuilder buffer = new StringBuilder(pattern);
final int split = pattern.indexOf(';');
if (split >= 0) {
buffer.insert(split, "E0");
}
buffer.append("E0");
decimalFormat.applyPattern(buffer.toString());
}
this.numberFormat = decimalFormat;
} else {
this.numberFormat = numberFormat;
exponentSymbol = null;
}
ignoredElements = new LinkedHashMap<>();
}
/**
* Returns the format string of the used number format. This method will return null, if the current number format is
* no instance of DecimalFormat.
*
* @return the formatstring of the number format instance.
*/
public String getFormatString() {
if ( getFormat() instanceof DecimalFormat ) {
final DecimalFormat decFormat = (DecimalFormat) getFormat();
return decFormat.toPattern();
}
return null;
}
public String convert(DecimalFormat obj) throws ConversionException {
return obj.toPattern();
}
/**
* Creates the number text element based on the defined settings. Undefined properties will not be set in the
* generated element.
*
* @return the generated numberic text element
* @see org.pentaho.reporting.engine.classic.core.elementfactory.ElementFactory#createElement()
*/
public Element createElement() {
final Element element = new Element();
if ( format instanceof DecimalFormat || format == null ) {
element.setElementType( new NumberFieldType() );
if ( getFieldname() != null ) {
element.setAttribute( AttributeNames.Core.NAMESPACE, AttributeNames.Core.FIELD, getFieldname() );
}
if ( getFormula() != null ) {
final FormulaExpression formulaExpression = new FormulaExpression();
formulaExpression.setFormula( getFormula() );
element.setAttributeExpression( AttributeNames.Core.NAMESPACE, AttributeNames.Core.VALUE, formulaExpression );
}
if ( format != null ) {
final DecimalFormat decimalFormat = (DecimalFormat) format;
final String formatString = decimalFormat.toPattern();
element.setAttribute( AttributeNames.Core.NAMESPACE, AttributeNames.Core.FORMAT_STRING, formatString );
}
element.setAttribute( AttributeNames.Core.NAMESPACE, AttributeNames.Core.NULL_VALUE, getNullString() );
} else {
final NumberFormatFilter dataSource = new NumberFormatFilter();
if ( format != null ) {
dataSource.setFormatter( format );
}
final DataRowDataSource dds = new DataRowDataSource();
if ( getFormula() != null ) {
dds.setFormula( getFormula() );
} else {
dds.setDataSourceColumnName( getFieldname() );
}
dataSource.setDataSource( dds );
if ( getNullString() != null ) {
dataSource.setNullValue( getNullString() );
}
element.setDataSource( dataSource );
}
applyElementName( element );
applyStyle( element.getStyle() );
element.getStyle().setStyleProperty( ElementStyleKeys.EXCEL_DATA_FORMAT_STRING, getExcelCellFormat() );
return element;
}