com.ibm.icu.text.DecimalFormat Java Examples

The following examples show how to use com.ibm.icu.text.DecimalFormat. 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: 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 #2
Source File: AutoScale.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
DecimalFormat getDecimalFormat()
{
	if ( this.si.fs == null ) // CREATE IF FORMAT SPECIFIER IS UNDEFINED
	{
		if ( !as.isBigNumber( ) )
		{
			this.df = as.computeDecimalFormat( dAxisValue, dAxisStep );
		}
		else
		{

			this.df = as.computeDecimalFormat( bdAxisValue.multiply( as.getBigNumberDivisor( ),
					NumberUtil.DEFAULT_MATHCONTEXT ), bdStep);
		}
	}
	return this.df;
}
 
Example #3
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 #4
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 #5
Source File: SeriesNameFormat.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
public String format( Object obj )
{
	String str = ""; //$NON-NLS-1$

	if ( obj != null )
	{
		if ( obj instanceof Number )
		{
			// TODO: use format cache to improve performance
			double d = ( (Number) obj ).doubleValue( );
			String sPattern = ValueFormatter.getNumericPattern( d );
			DecimalFormat df = new DecimalFormat( sPattern );
			str = df.format( d );
		}
		else
		{
			str = obj.toString( );
		}
	}

	return str;
}
 
Example #6
Source File: JavaNumberFormatSpecifierImpl.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
public String format( Number number, ULocale lo )
{
	Number n = NumberUtil.transformNumber( number );
	if ( n instanceof Double )
	{
		return format( ( (Double) n ).doubleValue( ), lo );
	}

	// Format big decimal
	BigDecimal bdNum = (BigDecimal) n;
	final DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance( lo );
	String vPattern = NumberUtil.adjustBigNumberFormatPattern( getPattern( ) );
	if ( vPattern.indexOf( 'E' ) < 0 )
	{
		vPattern = vPattern + NumberUtil.BIG_DECIMAL_FORMAT_SUFFIX;
	}
	df.applyPattern( vPattern );
	return isSetMultiplier( ) ? df.format( bdNum.multiply( BigDecimal.valueOf( getMultiplier( ) ),
			NumberUtil.DEFAULT_MATHCONTEXT ) )
			: df.format( bdNum );
}
 
Example #7
Source File: NumberFormatSpecifierImpl.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
public String format( double dValue, ULocale lo )
{
	final DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance( lo );
	if ( isSetFractionDigits( ) )
	{
		df.setMinimumFractionDigits( getFractionDigits( ) );
		df.setMaximumFractionDigits( getFractionDigits( ) );
	}

	df.applyLocalizedPattern( df.toLocalizedPattern( ) );

	final StringBuffer sb = new StringBuffer( );
	if ( getPrefix( ) != null )
	{
		sb.append( getPrefix( ) );
	}
	sb.append( isSetMultiplier( ) ? df.format( dValue * getMultiplier( ) )
			: df.format( dValue ) );
	if ( getSuffix( ) != null )
	{
		sb.append( getSuffix( ) );
	}

	return sb.toString( );
}
 
Example #8
Source File: JavaNumberFormatSpecifierImpl.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public String format( double dValue, ULocale lo )
{
	final DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance( lo );
	df.applyPattern( getPattern( ) );
	return isSetMultiplier( ) ? df.format( dValue * getMultiplier( ) )
			: df.format( dValue );
}
 
Example #9
Source File: NumberFormatSpecifierImpl.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public String format( Number number, ULocale lo )
{
	Number n = NumberUtil.transformNumber( number );
	if ( n instanceof Double )
	{
		return format( ( (Double) number ).doubleValue( ), lo );
	}

	// Format big decimal.
	BigDecimal bdNum = (BigDecimal) n;
	final DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance( lo );
	if ( isSetFractionDigits( ) )
	{
		df.setMinimumFractionDigits( getFractionDigits( ) );
		df.setMaximumFractionDigits( getFractionDigits( ) );
	}
	String pattern = NumberUtil.adjustBigNumberFormatPattern( df.toLocalizedPattern( ) );
	if ( pattern.indexOf( 'E' ) < 0 )
	{
		pattern = pattern + NumberUtil.BIG_DECIMAL_FORMAT_SUFFIX;
	}

	df.applyLocalizedPattern( pattern );

	final StringBuffer sb = new StringBuffer( );
	if ( getPrefix( ) != null )
	{
		sb.append( getPrefix( ) );
	}
	sb.append( isSetMultiplier( ) ? df.format( bdNum.multiply( BigDecimal.valueOf( getMultiplier( ) ),
			NumberUtil.DEFAULT_MATHCONTEXT ) )
			: df.format( bdNum ) );
	if ( getSuffix( ) != null )
	{
		sb.append( getSuffix( ) );
	}

	return sb.toString( );
}
 
Example #10
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 #11
Source File: ValueFormatterTest.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
public void testFormat2( ) throws ChartException
{
	assertEquals( "13.1", ValueFormatter.format( new Double( 13.1 ), null, null, new DecimalFormat( ) ) );//$NON-NLS-1$ 
	assertEquals( "13.1", ValueFormatter.format( NumberDataElementImpl.create( 13.1 ), null, null, new DecimalFormat( ) ) );//$NON-NLS-1$
}
 
Example #12
Source File: CronEditor.java    From bonita-studio with GNU General Public License v2.0 4 votes vote down vote up
protected void createHourlyTab(TabFolder tablFolder) {
    final TabItem item = new TabItem(tablFolder, SWT.NONE);
    item.setText(Messages.hourly);

    final Composite hourlyContent = new Composite(tablFolder, SWT.NONE);
    hourlyContent.setLayoutData(GridDataFactory.fillDefaults().grab(true, true).create());
    hourlyContent.setLayout(GridLayoutFactory.fillDefaults().numColumns(2).margins(15, 10).create());

    final Button everyRadio = new Button(hourlyContent, SWT.RADIO);
    everyRadio.setLayoutData(GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.CENTER).create());
    everyRadio.setText(Messages.every);

    context.bindValue(SWTObservables.observeSelection(everyRadio),
            PojoProperties.value("useEveryHour").observe(cronExpression));

    final Composite everyComposite = new Composite(hourlyContent, SWT.NONE);
    everyComposite.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).create());
    everyComposite.setLayout(GridLayoutFactory.fillDefaults().numColumns(2).margins(0, 0).create());

    final Text minuteText = new Text(everyComposite, SWT.BORDER | SWT.SINGLE);
    minuteText.setLayoutData(GridDataFactory.fillDefaults().hint(70, SWT.DEFAULT).create());

    UpdateValueStrategy hourFrequencyStrategy = new UpdateValueStrategy();
    hourFrequencyStrategy.setAfterGetValidator(dotValidator);
    hourFrequencyStrategy.setConverter(StringToNumberConverter.toInteger(true));
    hourFrequencyStrategy.setBeforeSetValidator(new FrequencyValidator());

    context.bindValue(SWTObservables.observeText(minuteText, SWT.Modify),
            PojoProperties.value("hourFrequencyForHourly").observe(cronExpression), hourFrequencyStrategy, null);

    final Label minuteLabel = new Label(everyComposite, SWT.NONE);
    minuteLabel.setLayoutData(GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.CENTER).create());
    minuteLabel.setText(Messages.hourLabel);

    final Button atRadio = new Button(hourlyContent, SWT.RADIO);
    atRadio.setLayoutData(GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.CENTER).create());
    atRadio.setText(Messages.at);

    final Composite atComposite = new Composite(hourlyContent, SWT.NONE);
    atComposite.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).create());
    atComposite.setLayout(GridLayoutFactory.fillDefaults().numColumns(3).margins(0, 0).create());

    final Combo hourCombo = new Combo(atComposite, SWT.READ_ONLY | SWT.BORDER);
    hourCombo.setItems(HOURS_IN_DAY);

    UpdateValueStrategy hourStrategy = new UpdateValueStrategy();
    hourStrategy.setConverter(StringToNumberConverter.toInteger(true));
    UpdateValueStrategy hourStrategy2 = new UpdateValueStrategy();

    NumberFormat formatter = new DecimalFormat("#00");
    hourStrategy2.setConverter(NumberToStringConverter.fromInteger(formatter, true));
    context.bindValue(SWTObservables.observeText(hourCombo),
            PojoProperties.value("atHour").observe(cronExpression), hourStrategy, hourStrategy2);

    final Combo minuteCombo = new Combo(atComposite, SWT.READ_ONLY | SWT.BORDER);
    minuteCombo.setItems(MINUTES_IN_HOURS);

    UpdateValueStrategy minuteStrategy = new UpdateValueStrategy();
    minuteStrategy.setConverter(StringToNumberConverter.toInteger(true));
    UpdateValueStrategy minuteStrategy2 = new UpdateValueStrategy();
    minuteStrategy2.setConverter(NumberToStringConverter.fromInteger(formatter, true));
    context.bindValue(SWTObservables.observeText(minuteCombo),
            PojoProperties.value("atMinute").observe(cronExpression), minuteStrategy, minuteStrategy2);

    final Combo secondCombo = new Combo(atComposite, SWT.READ_ONLY | SWT.BORDER);
    secondCombo.setItems(MINUTES_IN_HOURS);

    final IObservableValue secondObservable = PojoProperties.value("atSecond").observe(cronExpression);
    UpdateValueStrategy secondStrategy = new UpdateValueStrategy();
    secondStrategy.setConverter(StringToNumberConverter.toInteger(true));
    UpdateValueStrategy secondStrategy2 = new UpdateValueStrategy();
    secondStrategy2.setConverter(NumberToStringConverter.fromInteger(formatter, true));
    context.bindValue(SWTObservables.observeText(secondCombo), secondObservable, secondStrategy, secondStrategy2);

    item.setControl(hourlyContent);
}
 
Example #13
Source File: CronEditor.java    From bonita-studio with GNU General Public License v2.0 4 votes vote down vote up
protected Composite createStartTimeComposite(final Composite parentComposite,
        final IObservableValue hourObservable,
        final IObservableValue minuteObservable,
        final IObservableValue secondObservable) {
    final Composite timeComposite = new Composite(parentComposite, SWT.NONE);
    timeComposite.setLayoutData(GridDataFactory.fillDefaults().grab(true, true).span(2, 1).create());
    timeComposite.setLayout(GridLayoutFactory.fillDefaults().numColumns(4).create());

    final Label startTimeLabel = new Label(timeComposite, SWT.NONE);
    startTimeLabel.setText(Messages.startTime);

    final Combo hourCombo = new Combo(timeComposite, SWT.READ_ONLY | SWT.BORDER);
    hourCombo.setItems(HOURS_IN_DAY);

    NumberFormat formatter = new DecimalFormat("#00");
    UpdateValueStrategy hourStrategy = new UpdateValueStrategy();
    hourStrategy.setConverter(StringToNumberConverter.toInteger(true));

    UpdateValueStrategy hourStrategy2 = new UpdateValueStrategy();
    hourStrategy2.setConverter(NumberToStringConverter.fromInteger(formatter, true));

    context.bindValue(SWTObservables.observeText(hourCombo), hourObservable, hourStrategy, hourStrategy2);

    final Combo minuteCombo = new Combo(timeComposite, SWT.READ_ONLY | SWT.BORDER);
    minuteCombo.setItems(MINUTES_IN_HOURS);
    UpdateValueStrategy minuteStrategy = new UpdateValueStrategy();
    minuteStrategy.setConverter(StringToNumberConverter.toInteger(true));
    UpdateValueStrategy minuteStrategy2 = new UpdateValueStrategy();
    minuteStrategy2.setConverter(NumberToStringConverter.fromInteger(formatter, true));
    context.bindValue(SWTObservables.observeText(minuteCombo), minuteObservable, minuteStrategy, minuteStrategy2);

    final Combo secondCombo = new Combo(timeComposite, SWT.READ_ONLY | SWT.BORDER);
    secondCombo.setItems(MINUTES_IN_HOURS);
    UpdateValueStrategy secondStrategy = new UpdateValueStrategy();
    secondStrategy.setConverter(StringToNumberConverter.toInteger(true));
    UpdateValueStrategy secondStrategy2 = new UpdateValueStrategy();
    secondStrategy2.setConverter(NumberToStringConverter.fromInteger(formatter, true));
    context.bindValue(SWTObservables.observeText(secondCombo), secondObservable, secondStrategy, secondStrategy2);

    return timeComposite;
}
 
Example #14
Source File: ChartUtil.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected DecimalFormat newValue( String pattern )
{
	return new DecimalFormat( pattern,
			new DecimalFormatSymbols( locale ) );
}
 
Example #15
Source File: AutoScale.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Computes the default DecimalFormat pattern for axis according to axis
 * value and scale steps.
 * 
 * @param dAxisValue
 *            axis value
 * @param dAxisStep
 *            scale step
 * @return default format pattern
 */
public final DecimalFormat computeDecimalFormat( double dAxisValue,
		double dAxisStep )
{
	// Use a more precise pattern
	String valuePattern;
	String stepPattern;

	boolean bValuePrecise = false;
	boolean bStepPrecise = false;

	if ( this.isBigNumber( ) )
	{
		// return NumberUtil.getBigDecimalFormat( );
		BigDecimal bdAxisValue = this.getBigNumberDivisor( )
				.multiply( new BigDecimal( dAxisValue ),
						NumberUtil.DEFAULT_MATHCONTEXT );
		BigDecimal bdAxisStep = this.getBigNumberDivisor( )
				.multiply( new BigDecimal( dAxisStep ),
						NumberUtil.DEFAULT_MATHCONTEXT );
		
		valuePattern = ValueFormatter.getNumericPattern( bdAxisValue );
		stepPattern = ValueFormatter.getNumericPattern( bdAxisStep );

		bValuePrecise = ChartUtil.checkBigNumberPrecise( bdAxisValue );
		bStepPrecise = ChartUtil.checkBigNumberPrecise( bdAxisStep );
	}
	else
	{
		// Use a more precise pattern
		valuePattern = ValueFormatter.getNumericPattern( dAxisValue );

		// Since the axis step is computed, here normalize it first to avoid
		// error of precision and avoid to get error format pattern.
		dAxisStep = ValueFormatter.normalizeDouble( dAxisStep ).doubleValue( );
		stepPattern = ValueFormatter.getNumericPattern( dAxisStep );

		bValuePrecise = ChartUtil.checkDoublePrecise( dAxisValue );
		bStepPrecise = ChartUtil.checkDoublePrecise( dAxisStep );
	}

	// See Bugzilla#185883
	if ( bValuePrecise )
	{
		if ( bStepPrecise )
		{
			// If they are both double-precise, use the more precise one
			if ( valuePattern.length( ) < stepPattern.length( ) )
			{
				return info.cacheNumFormat.get( stepPattern );
			}
		}
	}
	else
	{
		if ( bStepPrecise )
		{
			return info.cacheNumFormat.get( stepPattern );
		}
		// If they are neither double-precise, use the default value
	}
	return info.cacheNumFormat.get( valuePattern );
}
 
Example #16
Source File: AutoScale.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
public final DecimalFormat computeDecimalFormat( BigDecimal bdAxisValue, BigDecimal bdAxisStep)
{
	if ( bdAxisValue.abs( ).compareTo( UPER_LIMIT ) >= 0
			|| bdAxisStep.abs( ).compareTo( UPER_LIMIT ) >= 0 )
	{
		return info.cacheNumFormat.get( "0.0E0" ); //$NON-NLS-1$
	}
	
	// Use a more precise pattern
	String valuePattern;
	String stepPattern;

	boolean bValuePrecise = false;
	boolean bStepPrecise = false;

	// return NumberUtil.getBigDecimalFormat( );
	valuePattern = ValueFormatter.getNumericPattern( bdAxisValue );
	stepPattern = ValueFormatter.getNumericPattern( bdAxisStep );

	bValuePrecise = ChartUtil.checkBigNumberPrecise( bdAxisValue );
	bStepPrecise = ChartUtil.checkBigNumberPrecise( bdAxisStep );

	// See Bugzilla#185883
	if ( bValuePrecise )
	{
		if ( bStepPrecise )
		{
			// If they are both double-precise, use the more precise one
			if ( valuePattern.length( ) < stepPattern.length( ) )
			{
				return info.cacheNumFormat.get( stepPattern );
			}
		}
	}
	else
	{
		if ( bStepPrecise )
		{
			return info.cacheNumFormat.get( stepPattern );
		}
		// If they are neither double-precise, use the default value
	}
	return info.cacheNumFormat.get( valuePattern );
}
 
Example #17
Source File: NumberFormatterImpl.java    From chart-fx with Apache License 2.0 4 votes vote down vote up
public DecimalFormat getFormatter() {
    return formatter;
}
 
Example #18
Source File: LogReader.java    From org.openntf.domino with Apache License 2.0 3 votes vote down vote up
/**
 * Converts the file size to a human readable format, e.g. "48 Kbytes"
 * 
 * @param size
 *            long file size
 * @return String file size in readable format
 * @since org.openntf.domino.xsp 2.5.0
 */
public static String readableFileSize(final long size) {
	if (size <= 0)
		return "0 bytes";
	final String[] units = new String[] { "bytes", "Kbytes", "Mb", "Gb", "Tb" };
	int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
	return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
 
Example #19
Source File: NumberUtil.java    From birt with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Returns a default format for big number.
 * 
 * @param locale
 * @return
 */
public static DecimalFormat getDefaultBigDecimalFormat(ULocale locale)
{
	return new DecimalFormat("0.##E0", new DecimalFormatSymbols( locale) ); //$NON-NLS-1$
}
 
Example #20
Source File: AutoScale.java    From birt with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Creates a default decimal format based on specified number.
 * 
 * @param number specified number.
 * @return instance of <code>DecimalFormat</code>
 */
public final DecimalFormat computeDefaultDecimalFormat( Number number )
{
	return info.cacheNumFormat.get( ValueFormatter.getNumericPattern( number ) );
}