Java Code Examples for java.text.DecimalFormat#toPattern()

The following examples show how to use java.text.DecimalFormat#toPattern() . 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: CurrencyValidator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * <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;
}
 
Example 2
Source File: Numerics.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 3
Source File: CurrencyEditText.java    From currency_edittext with Apache License 2.0 5 votes vote down vote up
/***
 * 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();
        }
    }
}
 
Example 4
Source File: NumberFormatParameter.java    From old-mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void saveValueToXML(@Nonnull Element xmlElement) {
  DecimalFormat format = getValue();
  if (format == null)
    return;
  String pattern = format.toPattern();
  xmlElement.setTextContent(pattern);
}
 
Example 5
Source File: DecimalFormatTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 6
Source File: FormatUtils.java    From syncope with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 7
Source File: FormatUtils.java    From syncope with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 8
Source File: AbstractParser.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * 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<>();
}
 
Example 9
Source File: NumberFieldElementFactory.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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;
}
 
Example 10
Source File: MiscConverters.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
public String convert(DecimalFormat obj) throws ConversionException {
    return obj.toPattern();
}
 
Example 11
Source File: NumberFieldElementFactory.java    From pentaho-reporting with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * 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;
}