java.text.NumberFormat Java Examples

The following examples show how to use java.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: AbstractXYItemLabelGenerator.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #2
Source File: MeterPlot.java    From astor with 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 #3
Source File: FormatMicroBenchmark.java    From jdk8u60 with 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 #4
Source File: ComplexFormat.java    From astor with 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 #5
Source File: Video.java    From Loop with 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 #6
Source File: CompositeFormat.java    From astor with 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 #7
Source File: SitePermissionHandler.java    From webcurator with 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 #8
Source File: FormatMicroBenchmark.java    From dragonwell8_jdk with 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 #9
Source File: PeerreviewServiceImpl.java    From lams with 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 #10
Source File: BoxAndWhiskerXYToolTipGenerator.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #11
Source File: MonetaryAmountDecimalFormatTest.java    From jsr354-ri with 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 #12
Source File: AbstractCategoryItemLabelGenerator.java    From buffer_bci with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a label generator with the specified number formatter.
 *
 * @param labelFormat  the label format string (<code>null</code> not
 *                     permitted).
 * @param formatter  the number formatter (<code>null</code> not permitted).
 * @param percentFormatter  the percent formatter (<code>null</code> not
 *     permitted).
 *
 * @since 1.0.2
 */
protected AbstractCategoryItemLabelGenerator(String labelFormat,
        NumberFormat formatter, NumberFormat percentFormatter) {
    ParamChecks.nullNotPermitted(labelFormat, "labelFormat");
    ParamChecks.nullNotPermitted(formatter, "formatter");
    ParamChecks.nullNotPermitted(percentFormatter, "percentFormatter");
    this.labelFormat = labelFormat;
    this.numberFormat = formatter;
    this.percentFormat = percentFormatter;
    this.dateFormat = null;
    this.nullValueString = "-";
}
 
Example #13
Source File: SPILocaleProviderAdapter.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
@Override
public NumberFormat getCompactNumberInstance(Locale locale,
                        NumberFormat.Style style) {
    locale = CalendarDataUtility.findRegionOverride(locale);
    NumberFormatProvider nfp = getImpl(locale);
    return nfp.getCompactNumberInstance(locale, style);
}
 
Example #14
Source File: ListObjectsIntegrationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #15
Source File: Matrix.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Print the matrix to the output stream. Line the elements up in columns with
 * a Fortran-like 'Fw.d' style format.
 *
 * @param aPW
 *        Output stream.
 * @param nWidth
 *        Column width.
 * @param nFractionDigits
 *        Number of digits after the decimal.
 */
public void print (@Nonnull final PrintWriter aPW,
                   @Nonnegative final int nWidth,
                   @Nonnegative final int nFractionDigits)
{
  final NumberFormat format = NumberFormat.getInstance (CGlobal.DEFAULT_LOCALE);
  format.setMinimumIntegerDigits (1);
  format.setMaximumFractionDigits (nFractionDigits);
  format.setMinimumFractionDigits (nFractionDigits);
  format.setGroupingUsed (false);
  print (aPW, format, nWidth + 2);
}
 
Example #16
Source File: TieRoundingTest.java    From openjdk-jdk9 with 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 #17
Source File: NumericFormatterFactory.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 #18
Source File: Support_DecimalFormat.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private static Vector<FieldContainer> getPositiveCurrencyVectorTR() {
  Vector<FieldContainer> v = new Vector<FieldContainer>();
  v.add(new FieldContainer(0, 1, NumberFormat.Field.CURRENCY));
  v.add(new FieldContainer(1, 4, NumberFormat.Field.INTEGER));
  v.add(new FieldContainer(4, 5, NumberFormat.Field.DECIMAL_SEPARATOR));
  v.add(new FieldContainer(5, 7, NumberFormat.Field.FRACTION));
  return v;
}
 
Example #19
Source File: Influx.java    From awacs with 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 #20
Source File: CourseGradeOverridePanel.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * 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 #21
Source File: BigFractionFormatTest.java    From astor with 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 #22
Source File: RRDatabase.java    From jrobin with 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 #23
Source File: FormatMicroBenchmark.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static String benchFormatFairSimple(NumberFormat nf, boolean isCurrency) {
    String str = "";
    double seed = isCurrency ?  0.0010203040506070809 : 0.00010203040506070809;
    double d = (double) -MAX_RANGE;
    for (int j = - MAX_RANGE; j <= MAX_RANGE; j++) {
        d = d  + 1.0d + seed;
        str = nf.format(d);
    }
    return str;
}
 
Example #24
Source File: RealVectorFormat.java    From astor with 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 #25
Source File: Analyze.java    From FancyBing with 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 #26
Source File: RealVectorFormat.java    From astor with 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 #27
Source File: ComplexFormatAbstractTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testGetImaginaryFormat() {
    NumberFormat nf = NumberFormat.getInstance();
    ComplexFormat cf = new ComplexFormat();

    assertNotSame(nf, cf.getImaginaryFormat());
    cf.setImaginaryFormat(nf);
    assertSame(nf, cf.getImaginaryFormat());
}
 
Example #28
Source File: NumberUtils.java    From OpenEstate-IO with 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 File: UIUtil.java    From consulo with 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
Source File: IntervalCategoryToolTipGeneratorTest.java    From openstock with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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));
}