Java Code Examples for java.text.NumberFormat

The following examples show how to use java.text.NumberFormat. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: astor   Source File: MeterPlot.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a new plot that displays the value from the supplied dataset.
 *
 * @param dataset  the dataset (<code>null</code> permitted).
 */
public MeterPlot(ValueDataset dataset) {
    super();
    this.shape = DialShape.CIRCLE;
    this.meterAngle = DEFAULT_METER_ANGLE;
    this.range = new Range(0.0, 100.0);
    this.tickSize = 10.0;
    this.tickPaint = Color.white;
    this.units = "Units";
    this.needlePaint = MeterPlot.DEFAULT_NEEDLE_PAINT;
    this.tickLabelsVisible = true;
    this.tickLabelFont = MeterPlot.DEFAULT_LABEL_FONT;
    this.tickLabelPaint = Color.black;
    this.tickLabelFormat = NumberFormat.getInstance();
    this.valueFont = MeterPlot.DEFAULT_VALUE_FONT;
    this.valuePaint = MeterPlot.DEFAULT_VALUE_PAINT;
    this.dialBackgroundPaint = MeterPlot.DEFAULT_DIAL_BACKGROUND_PAINT;
    this.intervals = new java.util.ArrayList();
    setDataset(dataset);
}
 
Example 2
Source Project: jdk8u60   Source File: FormatMicroBenchmark.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static String benchFormatFractionalAllNines(NumberFormat nf, boolean isCurrency) {
    String str = "";
    double fractionalEven = isCurrency ?  0.993000001 : 0.99930000001;
    double fractionalOdd  = isCurrency ?  0.996000001 : 0.99960000001;
    double fractional;
    double d;
    for (int j = - MAX_RANGE; j <= MAX_RANGE; j++) {
        if ((j & 1) == 0)
            fractional = fractionalEven;
        else
            fractional = fractionalOdd;
        if ( j >= 0)
            d = (double ) j + fractional;
        else d = (double) j - fractional;
        str = nf.format(d);
    }
    return str;
}
 
Example 3
Source Project: astor   Source File: ComplexFormat.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create an instance with a custom imaginary character, a custom number
 * format for the real part, and a custom number format for the imaginary
 * part.
 *
 * @param imaginaryCharacter The custom imaginary character.
 * @param realFormat the custom format for the real part.
 * @param imaginaryFormat the custom format for the imaginary part.
 * @throws NullArgumentException if {@code imaginaryCharacter} is
 * {@code null}.
 * @throws NoDataException if {@code imaginaryCharacter} is an
 * empty string.
 * @throws NullArgumentException if {@code imaginaryFormat} is {@code null}.
 * @throws NullArgumentException if {@code realFormat} is {@code null}.
 */
public ComplexFormat(String imaginaryCharacter,
                     NumberFormat realFormat,
                     NumberFormat imaginaryFormat) {
    if (imaginaryCharacter == null) {
        throw new NullArgumentException();
    }
    if (imaginaryCharacter.length() == 0) {
        throw new NoDataException();
    }
    if (imaginaryFormat == null) {
        throw new NullArgumentException(LocalizedFormats.IMAGINARY_FORMAT);
    }
    if (realFormat == null) {
        throw new NullArgumentException(LocalizedFormats.REAL_FORMAT);
    }

    this.imaginaryCharacter = imaginaryCharacter;
    this.imaginaryFormat = imaginaryFormat;
    this.realFormat = realFormat;
}
 
Example 4
Source Project: Loop   Source File: Video.java    License: Apache License 2.0 6 votes vote down vote up
public String getFormattedViewCount(){
    String formattedViewCount = "";

    int viewCount = 0;
    if (stats != null) {
        viewCount = stats.getPlays();
    }

    if (viewCount > 0) {
        formattedViewCount = NumberFormat.getNumberInstance(Locale.US).format(viewCount);
        if (viewCount > 1) {
            formattedViewCount = String.format("%s views", formattedViewCount);
        } else {
            formattedViewCount = String.format("%s view", formattedViewCount);
        }
    }
    return formattedViewCount;
}
 
Example 5
Source Project: astor   Source File: CompositeFormat.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parses <code>source</code> for a number.  This method can parse normal,
 * numeric values as well as special values.  These special values include
 * Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY.
 *
 * @param source the string to parse
 * @param format the number format used to parse normal, numeric values.
 * @param pos input/output parsing parameter.
 * @return the parsed number.
 */
public static Number parseNumber(final String source, final NumberFormat format,
                                 final ParsePosition pos) {
    final int startIndex = pos.getIndex();
    Number number = format.parse(source, pos);
    final int endIndex = pos.getIndex();

    // check for error parsing number
    if (startIndex == endIndex) {
        // try parsing special numbers
        final double[] special = {
            Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY
        };
        for (int i = 0; i < special.length; ++i) {
            number = parseNumber(source, special[i], pos);
            if (number != null) {
                break;
            }
        }
    }

    return number;
}
 
Example 6
Source Project: webcurator   Source File: SitePermissionHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
	super.initBinder(request, binder);
	
       NumberFormat nf = NumberFormat.getInstance(request.getLocale());	
       
       // Register the binders.
       binder.registerCustomEditor(Long.class, "selectedPermission", new CustomNumberEditor(Long.class, nf, true));
	binder.registerCustomEditor(java.util.Date.class, "startDate", DateUtils.get().getFullDateEditor(true));
	binder.registerCustomEditor(java.util.Date.class, "endDate", DateUtils.get().getFullDateEditor(true));
	
	// If the session model is available, we want to register the Permission's
	// authorising agency editor.
	if(getEditorContext(request) != null) {
		//binder.registerCustomEditor(AuthorisingAgent.class, new PermissionAuthAgencyEditor(sessionModel.getAuthorisingAgents()));
		binder.registerCustomEditor(AuthorisingAgent.class, "authorisingAgent", new EditorContextObjectEditor(getEditorContext(request), AuthorisingAgent.class));
		binder.registerCustomEditor(Set.class, "urls", new UrlPatternCollectionEditor(Set.class, true, getEditorContext(request)));
	}
}
 
Example 7
private static String benchFormatFractionalAllNines(NumberFormat nf, boolean isCurrency) {
    String str = "";
    double fractionalEven = isCurrency ?  0.993000001 : 0.99930000001;
    double fractionalOdd  = isCurrency ?  0.996000001 : 0.99960000001;
    double fractional;
    double d;
    for (int j = - MAX_RANGE; j <= MAX_RANGE; j++) {
        if ((j & 1) == 0)
            fractional = fractionalEven;
        else
            fractional = fractionalOdd;
        if ( j >= 0)
            d = (double ) j + fractional;
        else d = (double) j - fractional;
        str = nf.format(d);
    }
    return str;
}
 
Example 8
Source Project: lams   Source File: PeerreviewServiceImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
   public List<Object[]> getDetailedRatingsComments(Long toolContentId, Long toolSessionId, Long criteriaId,
    Long itemId) {
NumberFormat numberFormat = NumberFormat.getInstance(Locale.US);
numberFormat.setMaximumFractionDigits(1);

// raw data: user_id, comment, rating, first_name, last_name
List<Object[]> rawData = peerreviewUserDao.getDetailedRatingsComments(toolContentId, toolSessionId, criteriaId,
	itemId);
for (Object[] raw : rawData) {
    raw[2] = (raw[2] == null ? null : numberFormat.format(raw[2])); // format rating
    // format name
    StringBuilder description = new StringBuilder((String) raw[3]).append(" ").append((String) raw[4]);
    raw[4] = HtmlUtils.htmlEscape(description.toString());

}
return rawData;
   }
 
Example 9
/**
 * Creates the array of items that can be passed to the
 * {@link MessageFormat} class for creating labels.
 *
 * @param dataset  the dataset (<code>null</code> not permitted).
 * @param series  the series (zero-based index).
 * @param item  the item (zero-based index).
 *
 * @return The items (never <code>null</code>).
 */
protected Object[] createItemArray(XYDataset dataset, int series,
                                   int item) {
    Object[] result = new Object[8];
    result[0] = dataset.getSeriesKey(series).toString();
    Number x = dataset.getX(series, item);
    if (getXDateFormat() != null) {
        result[1] = getXDateFormat().format(new Date(x.longValue()));
    }
    else {
        result[1] = getXFormat().format(x);
    }
    NumberFormat formatter = getYFormat();

    if (dataset instanceof BoxAndWhiskerXYDataset) {
        BoxAndWhiskerXYDataset d = (BoxAndWhiskerXYDataset) dataset;
        result[2] = formatter.format(d.getMeanValue(series, item));
        result[3] = formatter.format(d.getMedianValue(series, item));
        result[4] = formatter.format(d.getMinRegularValue(series, item));
        result[5] = formatter.format(d.getMaxRegularValue(series, item));
        result[6] = formatter.format(d.getQ1Value(series, item));
        result[7] = formatter.format(d.getQ3Value(series, item));
    }
    return result;
}
 
Example 10
/**
 * Creates an item label generator using the specified number formatters.
 *
 * @param formatString  the item label format string (<code>null</code> 
 *                      not permitted).
 * @param xFormat  the format object for the x values (<code>null</code> 
 *                 not permitted).
 * @param yFormat  the format object for the y values (<code>null</code> 
 *                 not permitted).
 */
protected AbstractXYItemLabelGenerator(String formatString,
                                       NumberFormat xFormat, 
                                       NumberFormat yFormat) {

    if (formatString == null) {
        throw new IllegalArgumentException("Null 'formatString' argument.");
    }
    if (xFormat == null) {
        throw new IllegalArgumentException("Null 'xFormat' argument.");   
    }
    if (yFormat == null) {
        throw new IllegalArgumentException("Null 'yFormat' argument.");   
    }
    this.formatString = formatString;
    this.xFormat = xFormat;
    this.yFormat = yFormat;

}
 
Example 11
/**
 * Creates a new tool tip generator using default number formatters for the
 * x, y and z-values.
 */
public StandardXYZToolTipGenerator() {
    this(
        DEFAULT_TOOL_TIP_FORMAT,
        NumberFormat.getNumberInstance(),
        NumberFormat.getNumberInstance(),
        NumberFormat.getNumberInstance()
    );
}
 
Example 12
Source Project: SIMVA-SoS   Source File: StandardXYZToolTipGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new tool tip generator using default number formatters for the
 * x, y and z-values.
 */
public StandardXYZToolTipGenerator() {
    this(
        DEFAULT_TOOL_TIP_FORMAT,
        NumberFormat.getNumberInstance(),
        NumberFormat.getNumberInstance(),
        NumberFormat.getNumberInstance()
    );
}
 
Example 13
Source Project: jsr354-ri   Source File: MonetaryAmountDecimalFormatTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void setup() {
    Locale locale = Locale.US;
    currencyUnit = Monetary.getCurrency(locale);
    format = MonetaryAmountDecimalFormatBuilder.of(locale).withProducer(new MoneyProducer())
            .withCurrencyUnit(currencyUnit).build();
    numberFormat = NumberFormat.getCurrencyInstance(locale);
}
 
Example 14
Source Project: astor   Source File: RealVectorFormat.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create an instance with custom prefix, suffix, separator and format
 * for components.
 * @param prefix prefix to use instead of the default "{"
 * @param suffix suffix to use instead of the default "}"
 * @param separator separator to use instead of the default "; "
 * @param format the custom format for components.
 */
public RealVectorFormat(final String prefix, final String suffix,
                        final String separator, final NumberFormat format) {
    this.prefix      = prefix;
    this.suffix      = suffix;
    this.separator   = separator;
    trimmedPrefix    = prefix.trim();
    trimmedSuffix    = suffix.trim();
    trimmedSeparator = separator.trim();
    this.format      = format;
}
 
Example 15
Source Project: FancyBing   Source File: Analyze.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void writeHtmlRowPercentData(PrintStream out, String label,
                                     Statistics statistics,
                                     NumberFormat format) throws Exception
{
    String value;
    if (statistics.getCount() == 0)
        value = "";
    else
        value =
            format.format(statistics.getMean() * 100) + "% (&plusmn;"
            + format.format(statistics.getError() * 100) + ")";
    writeHtmlRow(out, label, value);
}
 
Example 16
public void testDenominatorFormat() {
    NumberFormat old = properFormat.getDenominatorFormat();
    NumberFormat nf = NumberFormat.getInstance();
    nf.setParseIntegerOnly(true);
    properFormat.setDenominatorFormat(nf);
    assertEquals(nf, properFormat.getDenominatorFormat());
    properFormat.setDenominatorFormat(old);

    old = improperFormat.getDenominatorFormat();
    nf = NumberFormat.getInstance();
    nf.setParseIntegerOnly(true);
    improperFormat.setDenominatorFormat(nf);
    assertEquals(nf, improperFormat.getDenominatorFormat());
    improperFormat.setDenominatorFormat(old);
}
 
Example 17
/**
 * Creates all the test resources for the tests.
 */
@BeforeClass
public static void createResources() throws Exception {
    createBucket(bucketName);

    NumberFormat numberFormatter = new DecimalFormat("##00");
    for (int i = 1; i <= BUCKET_OBJECTS; i++) {
        createKey("key-" + numberFormatter.format(i));
    }
    createKey("aaaaa");
    createKey("aaaaa/aaaaa/aaaaa");
    createKey("aaaaa/aaaaa+a");
    createKey("aaaaa/aaaaa//aaaaa");
    createKey(KEY_NAME_WITH_SPECIAL_CHARS);
}
 
Example 18
Source Project: java-technology-stack   Source File: CustomEditorTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testCustomNumberEditorWithFrenchBigDecimal() throws Exception {
	NumberFormat nf = NumberFormat.getNumberInstance(Locale.FRENCH);
	NumberTestBean tb = new NumberTestBean();
	BeanWrapper bw = new BeanWrapperImpl(tb);
	bw.registerCustomEditor(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, nf, true));
	bw.setPropertyValue("bigDecimal", "1000");
	assertEquals(1000.0f, tb.getBigDecimal().floatValue(), 0f);
	bw.setPropertyValue("bigDecimal", "1000,5");
	assertEquals(1000.5f, tb.getBigDecimal().floatValue(), 0f);
	bw.setPropertyValue("bigDecimal", "1 000,5");
	assertEquals(1000.5f, tb.getBigDecimal().floatValue(), 0f);
}
 
Example 19
Source Project: FancyBing   Source File: Analyze.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void writeData(File file) throws Exception
{
    PrintStream out = new PrintStream(file);
    NumberFormat format1 = StringUtil.getNumberFormat(1);
    NumberFormat format2 = StringUtil.getNumberFormat(3);
    Histogram histoBlack = m_statisticsBlack.m_histo;
    Histogram histoWhite = m_statisticsWhite.m_histo;
    Histogram histoReferee = m_statisticsReferee.m_histo;
    Statistics winBlack = m_statisticsBlack.m_win;
    Statistics winWhite = m_statisticsWhite.m_win;
    Statistics winReferee = m_statisticsReferee.m_win;
    Statistics unknownBlack = m_statisticsBlack.m_unknownScore;
    Statistics unknownWhite = m_statisticsWhite.m_unknownScore;
    Statistics unknownReferee = m_statisticsReferee.m_unknownScore;
    out.print("#GAMES\tERR\tDUP\tUSED\tRES_B\tERR_B\tWIN_B\tERRW_B\t"
              + "UNKN_B\tRES_W\tERR_W\tWIN_W\tERRW_W\tUNKN_W\t"
              + "RES_R\tERR_R\tWIN_R\tERRW_R\tUNKN_R\n" +
              m_games + "\t" + m_errors + "\t" + m_duplicates + "\t"
              + m_gamesUsed
              + "\t" + format1.format(histoBlack.getMean())
              + "\t" + format1.format(histoBlack.getError())
              + "\t" + format2.format(winBlack.getMean())
              + "\t" + format2.format(winBlack.getError())
              + "\t" + format2.format(unknownBlack.getMean())
              + "\t" + format1.format(histoWhite.getMean())
              + "\t" + format1.format(histoWhite.getError())
              + "\t" + format2.format(winWhite.getMean())
              + "\t" + format2.format(winWhite.getError())
              + "\t" + format2.format(unknownWhite.getMean())
              + "\t" + format1.format(histoReferee.getMean())
              + "\t" + format1.format(histoReferee.getError())
              + "\t" + format2.format(winReferee.getMean())
              + "\t" + format2.format(winReferee.getError())
              + "\t" + format2.format(unknownReferee.getMean())
              + "\n");
    out.close();
}
 
Example 20
Source Project: openjdk-jdk9   Source File: TieRoundingTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
static void formatOutputTestObject(NumberFormat nf,
                                   Object someNumber,
                                   String tiePosition,
                                   String inputDigits,
                                   String expectedOutput) {

    int mfd = nf.getMaximumFractionDigits();
    RoundingMode rm = nf.getRoundingMode();
    String result = nf.format(someNumber);

    if (!result.equals(expectedOutput)) {
        System.out.println();
        System.out.println("========================================");
        System.out.println("***Failure : error formatting value from string : " +
                           inputDigits);
        System.out.println("NumberFormat pattern is  : " +
                           ((DecimalFormat ) nf).toPattern());
        System.out.println("Maximum number of fractional digits : " + mfd);
        System.out.println("Fractional rounding digit : " + (mfd + 1));
        System.out.println("Position of value relative to tie : " + tiePosition);
        System.out.println("Rounding Mode : " + rm);
        System.out.println("Number self output representation: " + someNumber);
        System.out.println(
           "Error. Formatted result different from expected." +
           "\nExpected output is : \"" + expectedOutput + "\"" +
           "\nFormated output is : \"" + result + "\"");
        System.out.println("========================================");
        System.out.println();

        errorCounter++;
        allPassed = false;
    } else {
        testCounter++;
        System.out.print("Success. Number input :" + inputDigits);
        System.out.print(", rounding : " + rm);
        System.out.print(", fract digits : " + mfd);
        System.out.print(", tie position : " + tiePosition);
        System.out.println(", expected : " + expectedOutput);
    }
}
 
Example 21
/**
 * Check that the subclass is not equal to an instance of the superclass.
 */
@Test
public void testEquals2() {
    IntervalCategoryToolTipGenerator g1
            = new IntervalCategoryToolTipGenerator();
    StandardCategoryToolTipGenerator g2
            = new StandardCategoryToolTipGenerator(
            IntervalCategoryToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT_STRING,
            NumberFormat.getInstance());
    assertFalse(g1.equals(g2));
}
 
Example 22
public static NumericFormatter getDecimalFormatter(String formatString, Locale locale, int length, int scale) {
	NumberFormat numberFormat = createNumberFormatter(formatString, locale);
	
	if (numberFormat != null) {
		if( numberFormat instanceof DecimalFormat){
			((DecimalFormat) numberFormat).setParseBigDecimal(true);
		}
		return new JavaNumericFormatter(formatString, numberFormat);
	} else {
		return new JavolutionNumericFormatter(length);
	}
}
 
Example 23
Source Project: awacs   Source File: Influx.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected NumberFormat initialValue() {
    NumberFormat numberFormat = NumberFormat.getInstance(Locale.ENGLISH);
    numberFormat.setMaximumFractionDigits(MAX_FRACTION_DIGITS);
    numberFormat.setGroupingUsed(false);
    numberFormat.setMinimumFractionDigits(1);
    return numberFormat;
}
 
Example 24
/**
 * Helper to accept numerical grades and get the scale value. 
 * Returns the scale whose value equals to the numeric value received, or if it doesn't exists, the highest value lower.
 *
 * @param newGrade the grade to convert
 * @param schema the current schema of Gradebook
 * @param currentUserLocale the locale to format the grade with the right decimal separator
 * @return fully formatted string ready for display
 */
private String getGradeFromNumber(String newGrade, Map<String, Double> schema, Locale currentUserLocale) {
	Double currentGradeValue = new Double(0.0);
	Double maxValue = new Double(0.0);
	try	{
		NumberFormat nf = NumberFormat.getInstance(currentUserLocale);
		ParsePosition parsePosition = new ParsePosition(0);
		Number n = nf.parse(newGrade,parsePosition);
		if (parsePosition.getIndex() != newGrade.length()) 
			throw new NumberFormatException("Grade has a bad format.");
		Double dValue = n.doubleValue();
		
		for (Entry<String, Double> entry : schema.entrySet()) {
			Double tempValue = entry.getValue();
			if (dValue.equals(tempValue)) {
				return entry.getKey();
			}
			else {
				if (maxValue.compareTo(tempValue) < 0) maxValue=tempValue;
				if ((dValue.compareTo(tempValue) > 0 ) && (tempValue.compareTo(currentGradeValue) >= 0 )) {
					currentGradeValue = tempValue;
					newGrade=entry.getKey();
				}
			}
			if (dValue < 0) throw new NumberFormatException("Grade cannot be lower than 0.");
			if (dValue.compareTo(maxValue) > 0 && dValue > 100) throw new NumberFormatException("Grade exceeds the maximum number allowed in current scale.");
		}
		return newGrade;
	}
	catch (NumberFormatException e) {
		throw new NumberFormatException("Grade is not a number, neither a scale value.");
	}
}
 
Example 25
Source Project: astor   Source File: BigFractionFormatTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void testWholeFormat() {
    ProperBigFractionFormat format = (ProperBigFractionFormat)properFormat;
    
    NumberFormat old = format.getWholeFormat();
    NumberFormat nf = NumberFormat.getInstance();
    nf.setParseIntegerOnly(true);
    format.setWholeFormat(nf);
    assertEquals(nf, format.getWholeFormat());
    format.setWholeFormat(old);
}
 
Example 26
Source Project: jrobin   Source File: RRDatabase.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Outputs the header information of the database to the given print stream
 * using the given number format. The format is almost identical to that
 * produced by
 * <a href="http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/manual/rrdinfo.html">rrdtool info</a>
 *
 * @param s			the PrintStream to print the header information to.
 * @param numberFormat the format to print <code>double</code>s as.
 */
public void printInfo(PrintStream s, NumberFormat numberFormat) {

	s.print("filename = \"");
	s.print(name);
	s.println("\"");
	s.print("rrd_version = \"");
	s.print(header.version);
	s.println("\"");
	s.print("step = ");
	s.println(header.pdpStep);
	s.print("last_update = ");
	s.println(lastUpdate.getTime() / 1000);

	for (Iterator<DataSource> i = dataSources.iterator(); i.hasNext();) {
		DataSource ds = i.next();

		ds.printInfo(s, numberFormat);
	}

	int index = 0;

	for (Iterator<Archive> i = archives.iterator(); i.hasNext();) {
		Archive archive = i.next();

		archive.printInfo(s, numberFormat, index++);
	}
}
 
Example 27
Source Project: astor   Source File: RealVectorFormat.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create an instance with custom prefix, suffix, separator and format
 * for components.
 * @param prefix prefix to use instead of the default "{"
 * @param suffix suffix to use instead of the default "}"
 * @param separator separator to use instead of the default "; "
 * @param format the custom format for components.
 */
public RealVectorFormat(final String prefix, final String suffix,
                        final String separator, final NumberFormat format) {
    this.prefix      = prefix;
    this.suffix      = suffix;
    this.separator   = separator;
    trimmedPrefix    = prefix.trim();
    trimmedSuffix    = suffix.trim();
    trimmedSeparator = separator.trim();
    this.format      = format;
}
 
Example 28
Source Project: OpenEstate-IO   Source File: NumberUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Convert a string value into a number.
 *
 * @param value       the string value to convert
 * @param integerOnly wether only the integer part of the value is parsed
 * @param locales     locales, against which the value is parsed
 * @return numeric value for the string
 * @throws NumberFormatException if the string is not a valid number
 */
public static Number parseNumber(String value, boolean integerOnly, Locale... locales) throws NumberFormatException {
    value = StringUtils.trimToNull(value);
    if (value == null) return null;

    // ignore leading plus sign
    if (value.startsWith("+"))
        value = StringUtils.trimToNull(value.substring(1));

    // remove any spaces
    value = StringUtils.replace(value, StringUtils.SPACE, StringUtils.EMPTY);

    if (ArrayUtils.isEmpty(locales))
        locales = new Locale[]{Locale.getDefault()};

    for (Locale locale : locales) {
        // check, if the value is completely numeric for the locale
        if (!isNumeric(value, locale)) continue;
        NumberFormat format = NumberFormat.getNumberInstance(locale);
        try {
            format.setMinimumFractionDigits(0);
            format.setParseIntegerOnly(integerOnly);
            format.setGroupingUsed(value.indexOf(DecimalFormatSymbols.getInstance(locale).getGroupingSeparator()) > -1);
            return format.parse(value);
        } catch (ParseException ex) {
        }
    }
    throw new NumberFormatException("The provided value '" + value + "' is not numeric!");
}
 
Example 29
Source Project: consulo   Source File: UIUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * It is your responsibility to set correct horizontal align (left in case of UI Designer)
 */
public static void configureNumericFormattedTextField(@Nonnull JFormattedTextField textField) {
  NumberFormat format = NumberFormat.getIntegerInstance();
  format.setParseIntegerOnly(true);
  format.setGroupingUsed(false);
  NumberFormatter numberFormatter = new NumberFormatter(format);
  numberFormatter.setMinimum(0);
  textField.setFormatterFactory(new DefaultFormatterFactory(numberFormatter));
  textField.setHorizontalAlignment(SwingConstants.TRAILING);

  textField.setColumns(4);
}
 
Example 30
public void testGetImaginaryFormat() {
    NumberFormat nf = NumberFormat.getInstance();
    ComplexFormat cf = new ComplexFormat();

    assertNotSame(nf, cf.getImaginaryFormat());
    cf.setImaginaryFormat(nf);
    assertSame(nf, cf.getImaginaryFormat());
}