Java Code Examples for java.text.NumberFormat#parse()

The following examples show how to use java.text.NumberFormat#parse() . 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: EditTriggerFragment.java    From science-journal with Apache License 2.0 6 votes vote down vote up
private void saveTrigger(boolean returnToParent) {
  if (!verifyInput()) {
    return;
  }
  final DataController dc = getDataController();
  TriggerActionType triggerType =
      TriggerActionType.forNumber(typeSpinner.getSelectedItemPosition());
  TriggerWhen triggerWhen = TriggerWhen.forNumber(whenSpinner.getSelectedItemPosition());
  boolean triggerOnlyWhenRecording = onlyWhenRecording.isChecked();
  double triggerValue = 0;
  try {
    NumberFormat format = getValueNumberFormat();
    Number number = format.parse(value.getText().toString());
    triggerValue = number.doubleValue();
  } catch (ParseException ex) {
    value.setError(getActivity().getResources().getString(R.string.cannot_save_invalid_value));
    return;
  }
  if (isNewTrigger()) {
    createNewTrigger(dc, triggerType, triggerWhen, triggerValue, triggerOnlyWhenRecording);
  } else {
    updateTrigger(
        dc, triggerType, triggerWhen, triggerValue, triggerOnlyWhenRecording, returnToParent);
  }
}
 
Example 2
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/ouput parsing parameter.
 * @return the parsed number.
 */
protected 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 3
Source File: OctaneTest.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
protected Double filterBenchmark(final List<String> output, final String benchmarkName) throws Exception {
        Double currentScore = 0.;
        for (final String s : output) {
            //if (s.trim().startsWith(benchmarkName)) {
            if (s.trim().startsWith("Score")) {
                final String[] split = s.split(":");
                if (split.length != 2) {
                    for (final String outString : output) {
                        System.out.println("outString (score format)"+outString);
                    }
                    throw new IllegalArgumentException("Invalid benchmark output format");
                }

                final NumberFormat nf = NumberFormat.getInstance();
                final Number _newCurrentScore = nf.parse(split[1].trim());
                final Double newCurrentScore = _newCurrentScore.doubleValue();
                if (currentScore < newCurrentScore) {
                    currentScore = newCurrentScore;
                }
            }
        }
//        System.out.println("filterBenchmark current score:"+currentScore);
        return currentScore;
    }
 
Example 4
Source File: LocaleParser.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Nullable
public static Number parse (@Nullable final String sStr,
                            @Nonnull final NumberFormat aNF,
                            @Nullable final Number aDefault)
{
  ValueEnforcer.notNull (aNF, "NumberFormat");

  if (sStr != null)
    try
    {
      // parse throws a NPE if parameter is null
      return aNF.parse (sStr);
    }
    catch (final ParseException ex)
    {
      // fall through
    }

  // Return the provided default value
  return aDefault;
}
 
Example 5
Source File: Math_101_ComplexFormat_s.java    From coming with MIT License 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/ouput parsing parameter.
 * @return the parsed number.
 */
private Number parseNumber(String source, NumberFormat format, ParsePosition pos) {
    int startIndex = pos.getIndex();
    Number number = format.parse(source, pos);
    int endIndex = pos.getIndex();
    
    // check for error parsing number
    if (startIndex == endIndex) {
        // try parsing special numbers
        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 File: GenericTypeValidator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Checks if the value can safely be converted to a float primitive.
 *
 * @param value  The value validation is being performed on.
 * @param locale The locale to use to parse the number (system default if
 *               null)
 * @return the converted Float value.
 */
public static Float formatFloat(String value, Locale locale) {
    Float result = null;

    if (value != null) {
        NumberFormat formatter = null;
        if (locale != null) {
            formatter = NumberFormat.getInstance(locale);
        } else {
            formatter = NumberFormat.getInstance(Locale.getDefault());
        }
        ParsePosition pos = new ParsePosition(0);
        Number num = formatter.parse(value, pos);

        // If there was no error      and we used the whole string
        if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length() &&
                num.doubleValue() >= (Float.MAX_VALUE * -1) &&
                num.doubleValue() <= Float.MAX_VALUE) {
            result = new Float(num.floatValue());
        }
    }

    return result;
}
 
Example 7
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 8
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/ouput parsing parameter.
 * @return the parsed number.
 */
protected 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 9
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 10
Source File: NumberConverter.java    From hasor with Apache License 2.0 6 votes vote down vote up
/**
 * Convert a String into a <code>Number</code> object.
 * @param sourceType
 * @param targetType The type to convert the value to
 * @param value The String date value.
 * @param format The NumberFormat to parse the String value.
 *
 * @return The converted Number object.
 * @throws ConversionException if the String cannot be converted.
 */
private Number parse(final Class sourceType, final Class targetType, final String value, final NumberFormat format) {
    ParsePosition pos = new ParsePosition(0);
    Number parsedNumber = format.parse(value, pos);
    if (pos.getErrorIndex() >= 0 || pos.getIndex() != value.length() || parsedNumber == null) {
        String msg = "Error converting from '" + this.toString(sourceType) + "' to '" + this.toString(targetType) + "'";
        if (format instanceof DecimalFormat) {
            msg += " using pattern '" + ((DecimalFormat) format).toPattern() + "'";
        }
        if (this.locale != null) {
            msg += " for locale=[" + this.locale + "]";
        }
        throw new ConversionException(msg);
    }
    return parsedNumber;
}
 
Example 11
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/ouput parsing parameter.
 * @return the parsed number.
 */
protected 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 12
Source File: OctaneTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
protected Double filterBenchmark(final List<String> output, final String benchmarkName) throws Exception {
        Double currentScore = 0.;
        for (final String s : output) {
            //if (s.trim().startsWith(benchmarkName)) {
            if (s.trim().startsWith("Score")) {
                final String[] split = s.split(":");
                if (split.length != 2) {
                    for (final String outString : output) {
                        System.out.println("outString (score format)"+outString);
                    }
                    throw new IllegalArgumentException("Invalid benchmark output format");
                }

                final NumberFormat nf = NumberFormat.getInstance();
                final Number _newCurrentScore = nf.parse(split[1].trim());
                final Double newCurrentScore = _newCurrentScore.doubleValue();
                if (currentScore < newCurrentScore) {
                    currentScore = newCurrentScore;
                }
            }
        }
//        System.out.println("filterBenchmark current score:"+currentScore);
        return currentScore;
    }
 
Example 13
Source File: OctaneTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
protected Double filterBenchmark(final List<String> output, final String benchmarkName) throws Exception {
        Double currentScore = 0.;
        for (final String s : output) {
            //if (s.trim().startsWith(benchmarkName)) {
            if (s.trim().startsWith("Score")) {
                final String[] split = s.split(":");
                if (split.length != 2) {
                    for (final String outString : output) {
                        System.out.println("outString (score format)"+outString);
                    }
                    throw new IllegalArgumentException("Invalid benchmark output format");
                }

                final NumberFormat nf = NumberFormat.getInstance();
                final Number _newCurrentScore = nf.parse(split[1].trim());
                final Double newCurrentScore = _newCurrentScore.doubleValue();
                if (currentScore < newCurrentScore) {
                    currentScore = newCurrentScore;
                }
            }
        }
//        System.out.println("filterBenchmark current score:"+currentScore);
        return currentScore;
    }
 
Example 14
Source File: FilterMatcher.java    From jeveassets with GNU General Public License v2.0 5 votes vote down vote up
private static Number parse(final Object object, final NumberFormat numberFormat) {
	if (object instanceof String) {
		String filterValue = (String) object;
		//Used to check if parsing was successful
		ParsePosition position = new ParsePosition(0);
		//Parse number using the Locale
		Number n = numberFormat.parse(filterValue, position);
		if (n != null && position.getIndex() == filterValue.length()) { //Numeric
			return n;
		}
	}
	return null;
}
 
Example 15
Source File: ExampleUnitTest.java    From android with MIT License 5 votes vote down vote up
private void parse(Locale locale, float source) throws Exception {
    System.out.println(source);
    String parsedString = formatFloatWithOneDot(locale, source);
    System.out.println(parsedString);
    NumberFormat format = NumberFormat.getInstance(locale);
    Number parsedNumber = format.parse(parsedString);
    System.out.println(parsedNumber.floatValue());
    System.out.println(">>>>>>>>");
}
 
Example 16
Source File: LSIsCurrency.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public cfData execute( cfSession _session, List<cfData> parameters )throws cfmRunTimeException{      
   String currencyString = parameters.get(0).getString();
   boolean isIt = false;
   NumberFormat nf = NumberFormat.getCurrencyInstance( _session.getLocale() );
   
   if( currencyString != null ){
    try{
     nf.parse( currencyString );
     isIt = true;
    }catch( java.text.ParseException e ){
     isIt = false; }
   }
   
   return cfBooleanData.getcfBooleanData( isIt );
}
 
Example 17
Source File: GradebookServiceHibernateImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 *
 * @param doubleAsString
 * @return a locale-aware Double value representation of the given String
 * @throws ParseException
 */
private Double convertStringToDouble(final String doubleAsString) {
	Double scoreAsDouble = null;
	if (doubleAsString != null && !"".equals(doubleAsString)) {
		try {
			final NumberFormat numberFormat = NumberFormat.getInstance(new ResourceLoader().getLocale());
			final Number numericScore = numberFormat.parse(doubleAsString.trim());
			scoreAsDouble = numericScore.doubleValue();
		} catch (final ParseException e) {
			log.error(e.getMessage());
		}
	}

	return scoreAsDouble;
}
 
Example 18
Source File: DefaultTypeRegistry.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static Number parse( final NumberFormat format, final String source ) {
  final ParsePosition parsePosition = new ParsePosition( 0 );
  final Number result = format.parse( source, parsePosition );
  if ( parsePosition.getIndex() == 0 || parsePosition.getIndex() != source.length() ) {
    return null;
  }
  return result;
}
 
Example 19
Source File: UnitParser.java    From winter with Apache License 2.0 5 votes vote down vote up
public static Double transformUnit(String value, Unit unit) throws ParseException {
    value = value.replaceAll("[^0-9\\,\\.\\-Ee\\+]", "");
    NumberFormat format = NumberFormat.getInstance(Locale.US);
    Number number = format.parse(value);
    Double valueBeforeTransformation = number.doubleValue();
    return valueBeforeTransformation * unit.getFactor();
}
 
Example 20
Source File: LSParseNumber.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
protected static Number parseNumber( String _num, Locale _locale ) throws ParseException{
  NumberFormat numFormat = NumberFormat.getNumberInstance( _locale );
  return numFormat.parse( cleanNumber( _num ) );
}