java.text.DecimalFormat#parse ( )源码实例Demo

下面列出了java.text.DecimalFormat#parse ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: hop   文件: ActionZipFile.java
private int determineDepth( String depthString ) throws HopException {
  DecimalFormat df = new DecimalFormat( "0" );
  ParsePosition pp = new ParsePosition( 0 );
  df.setParseIntegerOnly( true );
  try {
    Number n = df.parse( depthString, pp );
    if ( n == null ) {
      return 1; // default
    }
    if ( pp.getErrorIndex() == 0 ) {
      throw new HopException( "Unable to convert stored depth '"
        + depthString + "' to depth at position " + pp.getErrorIndex() );
    }
    return n.intValue();
  } catch ( Exception e ) {
    throw new HopException( "Unable to convert stored depth '" + depthString + "' to depth", e );
  }
}
 
源代码2 项目: OpenLabeler   文件: AppUtils.java
public static TextFormatter createNumberTextFormatter() {
   DecimalFormat format = new DecimalFormat("#");
   return new TextFormatter<>(c -> {
      if (c.getControlNewText().isEmpty()) {
         return c;
      }
      ParsePosition parsePosition = new ParsePosition(0);
      Object object = format.parse(c.getControlNewText(), parsePosition);
      return (object == null || parsePosition.getIndex() < c.getControlNewText().length()) ? null : c;
   });
}
 
源代码3 项目: hop   文件: ValueMetaBase.java
protected synchronized Double convertStringToNumber( String string ) throws HopValueException {
  string = Const.trimToType( string, getTrimType() ); // see if trimming needs
  // to be performed before
  // conversion

  if ( Utils.isEmpty( string ) ) {
    return null;
  }

  try {
    DecimalFormat format = getDecimalFormat( false );
    Number number;
    if ( lenientStringToNumber ) {
      number = format.parse( string );
    } else {
      ParsePosition parsePosition = new ParsePosition( 0 );
      number = format.parse( string, parsePosition );

      if ( parsePosition.getIndex() < string.length() ) {
        throw new HopValueException( toString()
          + " : couldn't convert String to number : non-numeric character found at position "
          + ( parsePosition.getIndex() + 1 ) + " for value [" + string + "]" );
      }

    }

    return new Double( number.doubleValue() );
  } catch ( Exception e ) {
    throw new HopValueException( toString() + " : couldn't convert String to number ", e );
  }
}
 
源代码4 项目: phonegapbootcampsite   文件: Globalization.java
private JSONObject getStringToNumber(JSONArray options) throws GlobalizationError{
    JSONObject obj = new JSONObject();
    Number value;
    try{
        DecimalFormat fmt = getNumberFormatInstance(options); //returns Decimal/Currency/Percent instance
        value = fmt.parse((String)options.getJSONObject(0).get(NUMBERSTRING));
        return obj.put("value", value);
    }catch(Exception ge){
        throw new GlobalizationError(GlobalizationError.PARSING_ERROR);
    }
}
 
/**
 * Regardless of the default locale, comma ('.') is used as decimal separator
 *
 * @param source
 * @return
 * @throws ParseException
 */
public BigDecimal parse(String source) throws ParseException {
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setDecimalSeparator('.');
    DecimalFormat format = new DecimalFormat("#.#", symbols);
    format.setParseBigDecimal(true);
    return (BigDecimal) format.parse(source);
}
 
源代码6 项目: pentaho-kettle   文件: ValueMetaBase.java
protected synchronized Double convertStringToNumber( String string ) throws KettleValueException {
  string = Const.trimToType( string, getTrimType() ); // see if trimming needs
  // to be performed before
  // conversion

  if ( Utils.isEmpty( string ) ) {
    return null;
  }

  try {
    DecimalFormat format = getDecimalFormat( false );
    Number number;
    if ( lenientStringToNumber ) {
      number = format.parse( string );
    } else {
      ParsePosition parsePosition = new ParsePosition( 0 );
      number = format.parse( string, parsePosition );

      if ( parsePosition.getIndex() < string.length() ) {
        throw new KettleValueException( toString()
            + " : couldn't convert String to number : non-numeric character found at position "
            + ( parsePosition.getIndex() + 1 ) + " for value [" + string + "]" );
      }

    }

    return new Double( number.doubleValue() );
  } catch ( Exception e ) {
    throw new KettleValueException( toString() + " : couldn't convert String to number ", e );
  }
}
 
@Test
public void convert_formatted_string_to_number_java () throws ParseException {
	DecimalFormat df = new DecimalFormat("#,##0.00;(#,##0.00)");
	
	Number parsedNumber = df.parse("123,234.25");
	
	assertEquals(123234.25, parsedNumber);
}
 
源代码8 项目: JavaMainRepo   文件: CreateCFrame.java
/**
 * 
 * @return The salary.
 * @throws ParseException
 *             .
 */
public final BigDecimal getSalary() throws ParseException {
	DecimalFormatSymbols symbols = new DecimalFormatSymbols();
	symbols.setGroupingSeparator(',');
	symbols.setDecimalSeparator('.');
	String pattern = "#,##0.0#";
	DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
	decimalFormat.setParseBigDecimal(true);
	BigDecimal bigDecimal = (BigDecimal) decimalFormat.parse(salary.getText());
	return bigDecimal;
}
 
源代码9 项目: jpHolo   文件: Globalization.java
private JSONObject getStringToNumber(JSONArray options) throws GlobalizationError{
    JSONObject obj = new JSONObject();
    Number value;
    try{
        DecimalFormat fmt = getNumberFormatInstance(options); //returns Decimal/Currency/Percent instance
        value = fmt.parse((String)options.getJSONObject(0).get(NUMBERSTRING));
        return obj.put("value", value);
    }catch(Exception ge){
        throw new GlobalizationError(GlobalizationError.PARSING_ERROR);
    }
}
 
源代码10 项目: pippo   文件: ParameterValue.java
public BigDecimal toBigDecimal(BigDecimal defaultValue) {
    if (isNull() || StringUtils.isNullOrEmpty(values[0])) {
        return defaultValue;
    }

    DecimalFormat formatter = getDecimalFormat();
    formatter.setParseBigDecimal(true);
    try {
        return (BigDecimal) formatter.parse(values[0]);
    } catch (ParseException e) {
        throw new PippoRuntimeException(e, "Failed to parse '{}'", values[0]);
    }
}
 
源代码11 项目: commons-beanutils   文件: DecimalLocaleConverter.java
/**
 * Convert the specified locale-sensitive input object into an output
 * object of the specified type.
 *
 * @param value The input object to be converted
 * @param pattern The pattern is used for the conversion
 * @return The converted value
 *
 * @throws org.apache.commons.beanutils2.ConversionException if conversion
 * cannot be performed successfully
 * @throws ParseException if an error occurs parsing a String to a Number
 */
@Override
protected Object parse(final Object value, final String pattern) throws ParseException {

    if (value instanceof Number) {
        return value;
    }

    // Note that despite the ambiguous "getInstance" name, and despite the
    // fact that objects returned from this method have the same toString
    // representation, each call to getInstance actually returns a new
    // object.
    final DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(locale);

    // if some constructors default pattern to null, it makes only sense
    // to handle null pattern gracefully
    if (pattern != null) {
        if (locPattern) {
            formatter.applyLocalizedPattern(pattern);
        } else {
            formatter.applyPattern(pattern);
        }
    } else {
        log.debug("No pattern provided, using default.");
    }

    return formatter.parse((String) value);
}
 
源代码12 项目: j2objc   文件: DecimalFormatTest.java
public void test_parse_minusInfinityBigDecimalFalse() {
    // Regression test for HARMONY-106
    DecimalFormat format = (DecimalFormat) NumberFormat.getInstance();
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    Number number = format.parse("-" + symbols.getInfinity(),
            new ParsePosition(0));
    assertTrue(number instanceof Double);
    assertTrue(Double.isInfinite(number.doubleValue()));
}
 
public static Double getStringAsDouble(String numberAsString, String format)
{
    DecimalFormat df = new DecimalFormat(format);
    try
    {
        Number parse = df.parse(numberAsString);
        return parse.doubleValue();
    }

    catch ( ParseException e )
    {
        return PARSE_ERROR;
    }
}
 
源代码14 项目: development   文件: DurationValidation.java
/**
 * Parses the given value considering the current locale and returns the
 * number representation of the string. The representation is based on the
 * {@link #DURATION_FORMAT}.
 * 
 * @param valueToCheck
 *            The string to be parsed. Must not be <code>null</code>.
 * @return The number representation of the parameter.
 * @throws ParseException
 */
public static Number getParsedDuration(FacesContext facesContext,
        String valueToCheck) {
    Locale locale = LocaleHandler.getLocaleFromString(BaseBean
            .getUserFromSession(facesContext).getLocale());
    DecimalFormatSymbols dfs = new DecimalFormatSymbols(locale);
    DecimalFormat df = new DecimalFormat(DURATION_FORMAT, dfs);
    df.setGroupingUsed(true);
    try {
        return df.parse(valueToCheck);
    } catch (ParseException e) {
        return null;
    }
}
 
源代码15 项目: development   文件: DurationParameterValidator.java
/**
 * Taken from org.oscm.ui.common.DurationValidation
 * 
 * @param valueToCheck
 * @return
 */
private Number getParsedDuration(String valueToCheck) {
    DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.getDefault());
    DecimalFormat df = new DecimalFormat(DURATION_FORMAT, dfs);
    df.setGroupingUsed(true);
    try {
        return df.parse(valueToCheck);
    } catch (ParseException e) {
        return null;
    }
}
 
源代码16 项目: Pushjet-Android   文件: LocaleSafeDecimalFormat.java
/**
 * Regardless of the default locale, comma ('.') is used as decimal separator
 *
 * @param source
 * @return
 * @throws ParseException
 */
public BigDecimal parse(String source) throws ParseException {
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setDecimalSeparator('.');
    DecimalFormat format = new DecimalFormat("#.#", symbols);
    format.setParseBigDecimal(true);
    return (BigDecimal) format.parse(source);
}
 
源代码17 项目: Pushjet-Android   文件: LocaleSafeDecimalFormat.java
/**
 * Regardless of the default locale, comma ('.') is used as decimal separator
 *
 * @param source
 * @return
 * @throws ParseException
 */
public BigDecimal parse(String source) throws ParseException {
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setDecimalSeparator('.');
    DecimalFormat format = new DecimalFormat("#.#", symbols);
    format.setParseBigDecimal(true);
    return (BigDecimal) format.parse(source);
}
 
源代码18 项目: hop   文件: ValueMetaBase.java
protected synchronized BigDecimal convertStringToBigNumber( String string ) throws HopValueException {
  string = Const.trimToType( string, getTrimType() ); // see if trimming needs
  // to be performed before
  // conversion

  if ( Utils.isEmpty( string ) ) {
    return null;
  }

  try {
    DecimalFormat format = getDecimalFormat( bigNumberFormatting );
    Number number;
    if ( lenientStringToNumber ) {
      number = format.parse( string );
    } else {
      ParsePosition parsePosition = new ParsePosition( 0 );
      number = format.parse( string, parsePosition );

      if ( parsePosition.getIndex() < string.length() ) {
        throw new HopValueException( toString()
          + " : couldn't convert String to number : non-numeric character found at position "
          + ( parsePosition.getIndex() + 1 ) + " for value [" + string + "]" );
      }
    }

    // PDI-17366: Cannot simply cast a number to a BigDecimal,
    //            If the Number is not a BigDecimal.
    //
    if ( number instanceof Double ) {
      return BigDecimal.valueOf( number.doubleValue() );
    } else if ( number instanceof Long ) {
      return BigDecimal.valueOf( number.longValue() );
    }
    return (BigDecimal) number;

  } catch ( Exception e ) {
    // We added this workaround for PDI-1824
    //
    try {
      return new BigDecimal( string );
    } catch ( NumberFormatException ex ) {
      throw new HopValueException( toString() + " : couldn't convert string value '" + string
        + "' to a big number.", ex );
    }
  }
}
 
源代码19 项目: j2objc   文件: DecimalFormatTest.java
public void test_parse_withParsePosition() {
    DecimalFormat format = (DecimalFormat) NumberFormat.getNumberInstance(Locale.ENGLISH);
    ParsePosition pos = new ParsePosition(0);
    Number result = format.parse("9223372036854775807", pos);
    assertTrue("Wrong result type for Long.MAX_VALUE", result.getClass() == Long.class);
    assertTrue("Wrong result Long.MAX_VALUE", result.longValue() == Long.MAX_VALUE);
    pos = new ParsePosition(0);
    result = format.parse("-9223372036854775808", pos);
    assertTrue("Wrong result type for Long.MIN_VALUE", result.getClass() == Long.class);
    assertTrue("Wrong result Long.MIN_VALUE: " + result.longValue(),
            result.longValue() == Long.MIN_VALUE);
    pos = new ParsePosition(0);
    result = format.parse("9223372036854775808", pos);
    assertTrue("Wrong result type for Long.MAX_VALUE+1", result.getClass() == Double.class);
    assertTrue("Wrong result Long.MAX_VALUE + 1",
            result.doubleValue() == (double) Long.MAX_VALUE + 1);
    pos = new ParsePosition(0);
    result = format.parse("-9223372036854775809", pos);
    assertTrue("Wrong result type for Long.MIN_VALUE+1", result.getClass() == Double.class);
    assertTrue("Wrong result Long.MIN_VALUE - 1",
            result.doubleValue() == (double) Long.MIN_VALUE - 1);

    pos = new ParsePosition(0);
    result = format.parse("18446744073709551629", pos);
    assertTrue("Wrong result type for overflow", result.getClass() == Double.class);
    assertTrue("Wrong result for overflow", result.doubleValue() == 18446744073709551629d);

    pos = new ParsePosition(0);
    result = format.parse("42325917317067571199", pos);
    assertTrue("Wrong result type for overflow a: " + result,
            result.getClass() == Double.class);
    assertTrue("Wrong result for overflow a: " + result,
            result.doubleValue() == 42325917317067571199d);
    pos = new ParsePosition(0);
    result = format.parse("4232591731706757119E1", pos);
    assertTrue("Wrong result type for overflow b: " + result,
            result.getClass() == Double.class);
    assertTrue("Wrong result for overflow b: " + result,
            result.doubleValue() == 42325917317067571190d);
    pos = new ParsePosition(0);
    result = format.parse(".42325917317067571199E20", pos);
    assertTrue("Wrong result type for overflow c: " + result,
            result.getClass() == Double.class);
    assertTrue("Wrong result for overflow c: " + result,
            result.doubleValue() == 42325917317067571199d);
    pos = new ParsePosition(0);
    result = format.parse("922337203685477580.9E1", pos);
    assertTrue("Wrong result type for overflow d: " + result,
            result.getClass() == Double.class);
    assertTrue("Wrong result for overflow d: " + result,
            result.doubleValue() == 9223372036854775809d);
    pos = new ParsePosition(0);
    result = format.parse("9.223372036854775809E18", pos);
    assertTrue("Wrong result type for overflow e: " + result,
            result.getClass() == Double.class);
    assertTrue("Wrong result for overflow e: " + result,
            result.doubleValue() == 9223372036854775809d);
}
 
private Field convertStringToTargetType(
    Field field,
    Field.Type targetType,
    Locale dataLocale,
    String dateMask,
    int scale,
    DecimalScaleRoundingStrategy decimalScaleRoundingStrategy,
    DateTimeFormatter dateTimeFormatter
) throws ParseException {
  String stringValue = field.getValueAsString();
  switch(targetType) {
    case BOOLEAN:
      return Field.create(Field.Type.BOOLEAN, Boolean.valueOf(stringValue.trim()));
    case BYTE:
      return Field.create(NumberFormat.getInstance(dataLocale).parse(stringValue).byteValue());
    case BYTE_ARRAY:
      return Field.create(stringValue.getBytes(StandardCharsets.UTF_8));
    case CHAR:
      return Field.create(stringValue.charAt(0));
    case DATE:
      java.text.DateFormat dateFormat = new SimpleDateFormat(dateMask, Locale.ENGLISH);
      return Field.createDate(dateFormat.parse(stringValue.trim()));
    case DATETIME:
      java.text.DateFormat dateTimeFormat = new SimpleDateFormat(dateMask, Locale.ENGLISH);
      return Field.createDatetime(dateTimeFormat.parse(stringValue.trim()));
    case TIME:
      java.text.DateFormat timeFormat = new SimpleDateFormat(dateMask, Locale.ENGLISH);
      return Field.createTime(timeFormat.parse(stringValue.trim()));
    case ZONED_DATETIME:
      return Field.createZonedDateTime(ZonedDateTime.parse(stringValue.trim(), dateTimeFormatter));
    case DECIMAL:
      NumberFormat decimalFormat = NumberFormat.getInstance(dataLocale);
      DecimalFormat df = (DecimalFormat) decimalFormat;
      df.setParseBigDecimal(true);
      Number decimal = df.parse(stringValue.trim());
      BigDecimal bigDecimal = adjustScaleIfNeededForDecimalConversion(new BigDecimal(decimal.toString()), scale, decimalScaleRoundingStrategy);
      Field decimalField = Field.create(Field.Type.DECIMAL, bigDecimal);
      decimalField.setAttribute(HeaderAttributeConstants.ATTR_PRECISION, String.valueOf(bigDecimal.precision()));
      decimalField.setAttribute(HeaderAttributeConstants.ATTR_SCALE, String.valueOf(bigDecimal.scale()));
      return decimalField;
    case DOUBLE:
      return Field.create(NumberFormat.getInstance(dataLocale).parse(stringValue.trim()).doubleValue());
    case FLOAT:
      return Field.create(NumberFormat.getInstance(dataLocale).parse(stringValue.trim()).floatValue());
    case INTEGER:
      return Field.create(NumberFormat.getInstance(dataLocale).parse(stringValue.trim()).intValue());
    case LONG:
      return Field.create(NumberFormat.getInstance(dataLocale).parse(stringValue.trim()).longValue());
    case SHORT:
      return Field.create(NumberFormat.getInstance(dataLocale).parse(stringValue.trim()).shortValue());
    case FILE_REF:
      throw new IllegalArgumentException(Utils.format("Cannot convert String value to type {}", targetType));
    default:
      return field;
  }
}