com.ibm.icu.text.NumberFormat Java Examples

The following examples show how to use com.ibm.icu.text.NumberFormat. 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: NumberDataElementComposite.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
public DataElement getDataElement( )
{
	NumberFormat nf = ChartUIUtil.getDefaultNumberFormatInstance( );
	try
	{
		Number number = nf.parse( getText( ) );
		if (number instanceof BigInteger)
		{
			BigInteger biNumber = (BigInteger)number;
			return BigNumberDataElementImpl.create( new BigDecimal( biNumber ).stripTrailingZeros( ) );
		}
		return NumberDataElementImpl.create( number.doubleValue( ) );
	}
	catch ( ParseException e1 )
	{
		return null;
	}
}
 
Example #2
Source File: DataTypeUtil.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
public static BigDecimal toBigDecimalFromString( String s ) throws OdaException
{
	if ( s == null )
	{
		return null;
	}
	try
	{
		Number n = NumberFormat.getInstance( locale ).parse( s );
		return new BigDecimal( n.toString( ) );
	}
	catch ( ParseException e )
	{
		throw new OdaException( e );
	}
}
 
Example #3
Source File: ResultSet.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Transform a String value to an int value
 *
 * @param stringValue
 *            String value
 * @return Corresponding int value
 */
private int stringToInt(String stringValue) {
	if (stringValue != null) {
		try {
			//xls is returning doubles 
			return (int)Double.parseDouble(stringValue);
		} catch (NumberFormatException e) {
			try {
				Number number = NumberFormat
						.getInstance(JRE_DEFAULT_LOCALE).parse(stringValue);
				if (number != null) {
					return number.intValue();
				}
			} catch (ParseException e1) {
			}
		}
	}
	this.wasNull = true;
	return 0;
}
 
Example #4
Source File: ExcelUtil.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
private static String getCurrencySymbol( ULocale locale )
{
	NumberFormat format = NumberFormat.getCurrencyInstance( locale );
	Currency currency = format.getCurrency( );
	if ( currency != null )
	{
		String symbol = currency.getSymbol( locale );
		if ( symbol.equals( "EUR" ) )
		{
			symbol = "\u20ac"; // "€";
		}
		else if ( symbol.equals( "GBP" ) )
		{
			symbol = "\u00a3"; // "£";
		}
		else if ( symbol.equals( "XXX" ) )
		{
			symbol = "\u00a4"; // "¤";
		}
		return symbol;
	}
	return "$";
}
 
Example #5
Source File: ValueFormatter.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
public static Number normalizeDouble( Double dValue, String pattern )
{
	Number value = null;
	if ( pattern != null && pattern.trim( ).length( ) > 0 )
	{
		NumberFormat df = new DecimalFormat( pattern );

		String sValue = df.format( dValue );

		try
		{
			value = df.parse( sValue );
		}
		catch ( ParseException e )
		{
			logger.log( e );;
		}

	}
	else
	{
		value = normalizeDouble( dValue );
	}
	return value;
}
 
Example #6
Source File: ValueFormatter.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Normalize double value to avoid error precision.
 * 
 * @param value
 * @return normalized value of specified double.
 */
public static Number normalizeDouble( Double value )
{
	if ( value.isNaN( ) )
	{
		return 0;
	}
	
	NumberFormat df = createDefaultNumberFormat( value, ULocale.ENGLISH );

	// Normalize double value to avoid double precision error.
	String sValue = df.format( value );
	try
	{
		return df.parse( sValue );
	}
	catch ( ParseException e )
	{
		logger.log( e );
	}
	
	return value;
}
 
Example #7
Source File: ResultSet.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Transform a String value to a double value
 *
 * @param stringValue
 *            String value
 * @return Corresponding double value
 */
private double stringToDouble(String stringValue) {
	if (stringValue != null) {
		try {
			return Double.parseDouble(stringValue);
		} catch (NumberFormatException e) {
			try {
				Number number = NumberFormat
						.getInstance(JRE_DEFAULT_LOCALE).parse(stringValue);
				if (number != null) {
					return number.doubleValue();
				}
			} catch (ParseException e1) {
			}
		}
	}
	this.wasNull = true;
	return 0;
}
 
Example #8
Source File: SeriesRegionSheet.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
private DataElement getTypedDataElement( String strDataElement )
{
	if ( strDataElement == null )
	{
		return null;
	}
	if ( strDataElement.trim( ).length( ) == 0 )
	{
		return NumberDataElementImpl.create( 0.0 );
	}
	NumberFormat nf = ChartUIUtil.getDefaultNumberFormatInstance( );

	try
	{
		Number numberElement = nf.parse( strDataElement );
		return NumberDataElementImpl.create( numberElement.doubleValue( ) );
	}
	catch ( ParseException e1 )
	{
		return NumberDataElementImpl.create( 0.0 );
	}
}
 
Example #9
Source File: FormatPercentNumPattern.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the default percent symbol position for given locale
 * 
 * @param locale
 * @return
 */
public static String getDefaultSymbolPosition( ULocale locale )
{
	if ( locale == null )
	{
		locale = ULocale.getDefault( );
	}

	NumberFormat formater = NumberFormat.getPercentInstance( locale );
	String result = formater.format( 1 );
	if ( result.endsWith( "%" ) ) //$NON-NLS-1$
	{
		return FormatNumberPattern.SYMBOL_POSITION_AFTER;
	}
	else
	{
		return FormatNumberPattern.SYMBOL_POSITION_BEFORE;
	}
}
 
Example #10
Source File: FormatNumberLayoutPeer.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
private boolean isValidNumber( String text )
{
	ULocale locale = getLocaleByDisplayName( localeChoicer.getText( ) );
	if ( locale == null )
	{
		locale = ULocale.getDefault( );
	}

	try
	{
		NumberFormat.getNumberInstance( locale ).parse( text );
		return true;
	}
	catch ( ParseException e )
	{
	}
	return false;
}
 
Example #11
Source File: ResultSet.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Transform a String value to a big decimal value
 *
 * @param stringValue
 *            String value
 * @return Corresponding BigDecimal value
 */
private BigDecimal stringToBigDecimal(String stringValue) {
	if (stringValue != null) {
		try {
			return new BigDecimal(stringValue);
		} catch (NumberFormatException e) {
			try {
				Number number = NumberFormat
						.getInstance(JRE_DEFAULT_LOCALE).parse(stringValue);
				if (number != null) {
					return new BigDecimal(number.toString());
				}
			} catch (ParseException e1) {
			}
		}
	}
	this.wasNull = true;
	return null;
}
 
Example #12
Source File: RadarLineSheet.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
private double getTypedDataElement( String strDataElement )
{
	if ( strDataElement.trim( ).length( ) == 0 )
	{
		return 0.0;
	}
	NumberFormat nf = ChartUIUtil.getDefaultNumberFormatInstance( );

	try
	{
		Number numberElement = nf.parse( strDataElement );
		return numberElement.doubleValue( );
	}
	catch ( ParseException e1 )
	{
		return 0.0;
	}
}
 
Example #13
Source File: PluralRulesObject.java    From es6draft with MIT License 6 votes vote down vote up
private NumberFormat createNumberFormat() {
    ULocale locale = ULocale.forLanguageTag(this.locale);
    locale = locale.setKeywordValue("numbers", "latn");

    DecimalFormat numberFormat = (DecimalFormat) NumberFormat.getInstance(locale, NumberFormat.NUMBERSTYLE);
    if (minimumSignificantDigits != 0 && maximumSignificantDigits != 0) {
        numberFormat.setSignificantDigitsUsed(true);
        numberFormat.setMinimumSignificantDigits(minimumSignificantDigits);
        numberFormat.setMaximumSignificantDigits(maximumSignificantDigits);
    } else {
        numberFormat.setSignificantDigitsUsed(false);
        numberFormat.setMinimumIntegerDigits(minimumIntegerDigits);
        numberFormat.setMinimumFractionDigits(minimumFractionDigits);
        numberFormat.setMaximumFractionDigits(maximumFractionDigits);
    }
    // as required by ToRawPrecision/ToRawFixed
    numberFormat.setRoundingMode(BigDecimal.ROUND_HALF_UP);
    return numberFormat;
}
 
Example #14
Source File: PluralRulesObject.java    From es6draft with MIT License 6 votes vote down vote up
@SuppressWarnings("deprecation")
com.ibm.icu.text.PluralRules.FixedDecimal toFixedDecimal(double n) {
    NumberFormat nf = getNumberFormat();

    StringBuffer sb = new StringBuffer();
    FieldPosition fp = new FieldPosition(DecimalFormat.FRACTION_FIELD);
    nf.format(n, sb, fp);

    int v = fp.getEndIndex() - fp.getBeginIndex();
    long f = 0;
    if (v > 0) {
        ParsePosition pp = new ParsePosition(fp.getBeginIndex());
        f = nf.parse(sb.toString(), pp).longValue();
    }
    return new com.ibm.icu.text.PluralRules.FixedDecimal(n, v, f);
}
 
Example #15
Source File: FormatterImpl.java    From org.openntf.domino with Apache License 2.0 6 votes vote down vote up
public Number parseNumber(String image, final boolean lenient) {
	image = image.trim();
	if (!image.isEmpty()) {
		String toParse = image;
		if (toParse.length() > 1 && toParse.charAt(0) == '+')
			toParse = toParse.substring(1);
		NumberFormat nf = NumberFormat.getNumberInstance(iLocale);
		ParsePosition p = new ParsePosition(0);
		Number ret = nf.parse(toParse, p);
		int errIndex = p.getErrorIndex();
		//System.out.println("Ind=" + index + " ErrInd=" + errIndex);
		if (errIndex == -1) {
			if (p.getIndex() >= toParse.length() || lenient)
				return ret;
		} else if (errIndex != 0 && lenient)
			return ret;
	}
	throw new IllegalArgumentException("Illegal number string '" + image + "'");
}
 
Example #16
Source File: DataTypeUtil.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public static Byte toByteFromString( String s ) throws OdaException
{
	if ( s == null )
	{
		return null;
	}
	try
	{
		return Byte.valueOf(NumberFormat.getInstance( locale ).parse( s ).byteValue( ));
	}
	catch ( ParseException e )
	{
		throw new OdaException( e );
	}
}
 
Example #17
Source File: DataTypeUtil.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public static Integer toIntegerFromString( String s ) throws OdaException
{
	if ( s == null )
	{
		return null;
	}
	try
	{
		return Integer.valueOf(NumberFormat.getInstance( locale ).parse( s ).intValue( ));
	}
	catch ( ParseException e )
	{
		throw new OdaException( e );
	}
}
 
Example #18
Source File: NumberFormatService.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Format a number to localized number by scale
 * @param locale
 * @param number
 * @param scale
 * @return Localized number
 */
public String formatNumber(String locale, String number, int scale) {
    Number num = this.parseNumber(number);
	ULocale uLocale = new ULocale(locale);
	NumberFormat numberFormat = NumberFormat.getNumberInstance(uLocale);
	numberFormat.setMaximumFractionDigits(scale);
	numberFormat.setMinimumFractionDigits(scale);
	numberFormat.setRoundingMode(BigDecimal.ROUND_HALF_UP);
	return numberFormat.format(num);
}
 
Example #19
Source File: DataTypeUtil.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public static Double toDoubleFromString( String s ) throws OdaException
{
	if ( s == null )
	{
		return null;
	}
	try
	{
		return Double.valueOf(NumberFormat.getInstance( locale ).parse( s ).doubleValue( ));
	}
	catch ( ParseException e )
	{
		throw new OdaException( e );
	}
}
 
Example #20
Source File: OdsUtil.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
private static String getCurrencySymbol( ULocale locale )
{
	NumberFormat format = NumberFormat.getCurrencyInstance( locale );
	Currency currency = format.getCurrency( );
	if ( currency != null )
	{
		String symbol = currency.getSymbol( locale );
	if ( symbol.equals( "EUR" ) )
	{
		symbol = "€";
	}
	if ( symbol.equals( "GBP" ) )
	{
		symbol = "£";
	}
	if ( symbol.equals( "XXX" ) )
	{
		symbol = "¤";
	}
	if ( symbol == null )
	{
		symbol = "$";
	}
	return symbol;
	}
	return "$";
}
 
Example #21
Source File: FormatCurrencyNumPattern.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the default currency symbol position for given locale. Returns
 * <code>null</code> if no symbol needed by default.
 * 
 * @param locale
 * @return
 */
public static String getDefaultSymbolPosition( ULocale locale )
{
	if ( locale == null )
	{
		locale = ULocale.getDefault( );
	}

	Currency currency = Currency.getInstance( locale );
	if ( currency != null )
	{
		String symbol = currency.getSymbol( );
		if ( symbol == null )
		{
			return null;
		}
		NumberFormat formater = NumberFormat.getCurrencyInstance( locale );
		String result = formater.format( 1 );
		if ( result.endsWith( symbol ) )
		{
			return FormatNumberPattern.SYMBOL_POSITION_AFTER;
		}
		else
		{
			return FormatNumberPattern.SYMBOL_POSITION_BEFORE;
		}
	}
	return null;
}
 
Example #22
Source File: NumberFormatConstructor.java    From es6draft with MIT License 5 votes vote down vote up
/**
 * PartitionNumberPattern(numberFormat, x)
 * 
 * @param numberFormatObj
 *            the number format object
 * @param x
 *            the number value
 * @return the formatted number object
 */
private static List<Map.Entry<String, String>> PartitionNumberPattern(NumberFormatObject numberFormat, double x) {
    if (x == -0.0) {
        // -0 is not considered to be negative, cf. step 3a
        x = +0.0;
    }
    ArrayList<Map.Entry<String, String>> parts = new ArrayList<>();
    NumberFormat numFormat = numberFormat.getNumberFormat();
    AttributedCharacterIterator iterator = numFormat.formatToCharacterIterator(x);
    StringBuilder sb = new StringBuilder();
    for (char ch = iterator.first(); ch != CharacterIterator.DONE; ch = iterator.next()) {
        sb.append(ch);
        if (iterator.getIndex() + 1 == iterator.getRunLimit()) {
            Iterator<Attribute> keyIterator = iterator.getAttributes().keySet().iterator();
            String key;
            if (keyIterator.hasNext()) {
                key = fieldToString((NumberFormat.Field) keyIterator.next(), x);
            } else {
                key = "literal";
            }
            String value = sb.toString();
            sb.setLength(0);
            parts.add(new AbstractMap.SimpleImmutableEntry<>(key, value));
        }
    }
    return parts;
}
 
Example #23
Source File: NumberFormatObject.java    From es6draft with MIT License 5 votes vote down vote up
/**
 * Returns the ICU {@link NumberFormat} instance.
 * 
 * @return the NumberFormat instance
 */
public NumberFormat getNumberFormat() {
    if (numberFormat == null) {
        numberFormat = createNumberFormat();
    }
    return numberFormat;
}
 
Example #24
Source File: NumberFormatObject.java    From es6draft with MIT License 5 votes vote down vote up
private NumberFormat createNumberFormat() {
    ULocale locale = ULocale.forLanguageTag(this.locale);
    int choice;
    if ("decimal".equals(style)) {
        choice = NumberFormat.NUMBERSTYLE;
    } else if ("percent".equals(style)) {
        choice = NumberFormat.PERCENTSTYLE;
    } else {
        if ("code".equals(currencyDisplay)) {
            choice = NumberFormat.ISOCURRENCYSTYLE;
        } else if ("symbol".equals(currencyDisplay)) {
            choice = NumberFormat.CURRENCYSTYLE;
        } else {
            choice = NumberFormat.PLURALCURRENCYSTYLE;
        }
    }
    DecimalFormat numberFormat = (DecimalFormat) NumberFormat.getInstance(locale, choice);
    if ("currency".equals(style)) {
        numberFormat.setCurrency(Currency.getInstance(currency));
    }
    // numberingSystem is already handled in language-tag
    // assert locale.getKeywordValue("numbers").equals(numberingSystem);
    if (minimumSignificantDigits != 0 && maximumSignificantDigits != 0) {
        numberFormat.setSignificantDigitsUsed(true);
        numberFormat.setMinimumSignificantDigits(minimumSignificantDigits);
        numberFormat.setMaximumSignificantDigits(maximumSignificantDigits);
    } else {
        numberFormat.setSignificantDigitsUsed(false);
        numberFormat.setMinimumIntegerDigits(minimumIntegerDigits);
        numberFormat.setMinimumFractionDigits(minimumFractionDigits);
        numberFormat.setMaximumFractionDigits(maximumFractionDigits);
    }
    numberFormat.setGroupingUsed(useGrouping);
    // as required by ToRawPrecision/ToRawFixed
    // FIXME: ICU4J bug:
    // new Intl.NumberFormat("en",{useGrouping:false}).format(111111111111111)
    // returns "111111111111111.02"
    numberFormat.setRoundingMode(BigDecimal.ROUND_HALF_UP);
    return numberFormat;
}
 
Example #25
Source File: DataTypeUtil.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public static Float toFloatFromString( String s ) throws OdaException
{
	if ( s == null )
	{
		return null;
	}
	try
	{
		return Float.valueOf(NumberFormat.getInstance( locale ).parse( s ).floatValue( ));
	}
	catch ( ParseException e )
	{
		throw new OdaException( e );
	}
}
 
Example #26
Source File: ResultSet.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Transform a string to boolean value
 *
 * @param stringValue
 * @return
 */
private Boolean stringToBoolean(String stringValue) {
	if (stringValue != null) {
		if (stringValue.equalsIgnoreCase("true")) //$NON-NLS-1$
			return Boolean.TRUE;
		else if (stringValue.equalsIgnoreCase("false")) //$NON-NLS-1$
			return Boolean.FALSE;
		else {
			try {
				if (Integer.parseInt((String) stringValue) == 0)
					return Boolean.FALSE;
				else
					return Boolean.TRUE;
			} catch (NumberFormatException e) {
				try {
					Number number = NumberFormat.getInstance(
							JRE_DEFAULT_LOCALE).parse(stringValue);
					if (number != null) {
						return number.intValue() == 0 ? Boolean.FALSE
								: Boolean.TRUE;
					}
				} catch (ParseException e1) {
				}
			}
		}
	}
	return Boolean.FALSE;
}
 
Example #27
Source File: ChartUIUtil.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the default number format instance for default locale.
 * 
 * @return the default number format
 */
public static NumberFormat getDefaultNumberFormatInstance( )
{
	NumberFormat numberFormat = NumberFormat.getInstance( );
	// fix icu limitation which only allow 3 fraction digits as maximum by
	// default. ?100 is enough.
	numberFormat.setMaximumFractionDigits( 100 );
	return numberFormat;
}
 
Example #28
Source File: DataTypeUtil.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public static Short toShortFromString( String s ) throws OdaException
{
	if ( s == null )
	{
		return null;
	}
	try
	{
		return Short.valueOf(NumberFormat.getInstance( locale ).parse( s ).shortValue( ));
	}
	catch ( ParseException e )
	{
		throw new OdaException( e );
	}
}
 
Example #29
Source File: NumberFormatService.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Parse a number string to number
 * @param numberStr
 * @return number
 */
private Number parseNumber(String numberStr){
    try {
           return NumberFormat.getNumberInstance().parse(numberStr);
       } catch (ParseException e) {
       	logger.error(e.getMessage(), e);
           return 0;
       }
}
 
Example #30
Source File: GlobalizationPreferences.java    From fitnotifications with Apache License 2.0 5 votes vote down vote up
/**
 * Sets a number format explicitly. Overrides the general locale settings.
 *
 * @param style NF_NUMBER, NF_CURRENCY, NF_PERCENT, NF_SCIENTIFIC, NF_INTEGER
 * @param format The number format
 * @return this, for chaining
 * @draft ICU 3.6
 * @provisional This API might change or be removed in a future release.
 */
public GlobalizationPreferences setNumberFormat(int style, NumberFormat format) {
    if (isFrozen()) {
        throw new UnsupportedOperationException("Attempt to modify immutable object");
    }
    if (numberFormats == null) {
        numberFormats = new NumberFormat[NF_LIMIT];
    }
    numberFormats[style] = (NumberFormat) format.clone(); // for safety
    return this;
}