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

The following examples show how to use java.text.DecimalFormat#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: ActionZipFile.java    From hop with Apache License 2.0 6 votes vote down vote up
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 );
  }
}
 
Example 2
Source File: CreateCFrame.java    From JavaMainRepo with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @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;
}
 
Example 3
Source File: LocaleSafeDecimalFormat.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * 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);
}
 
Example 4
Source File: LocaleSafeDecimalFormat.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * 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);
}
 
Example 5
Source File: DurationParameterValidator.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
    }
}
 
Example 6
Source File: DurationValidation.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
    }
}
 
Example 7
Source File: StringUtils.java    From privacy-friendly-shopping-list with Apache License 2.0 5 votes vote down vote up
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;
    }
}
 
Example 8
Source File: DecimalFormatTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
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()));
}
 
Example 9
Source File: DecimalLocaleConverter.java    From commons-beanutils with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 10
Source File: ParameterValue.java    From pippo with Apache License 2.0 5 votes vote down vote up
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]);
    }
}
 
Example 11
Source File: Globalization.java    From jpHolo with MIT License 5 votes vote down vote up
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);
    }
}
 
Example 12
Source File: AppUtils.java    From OpenLabeler with Apache License 2.0 5 votes vote down vote up
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;
   });
}
 
Example 13
Source File: FormattedStringToNumber.java    From levelup-java-examples with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 14
Source File: ValueMetaBase.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
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 );
  }
}
 
Example 15
Source File: LocaleSafeDecimalFormat.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * 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);
}
 
Example 16
Source File: Globalization.java    From phonegapbootcampsite with MIT License 5 votes vote down vote up
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);
    }
}
 
Example 17
Source File: ValueMetaBase.java    From hop with Apache License 2.0 5 votes vote down vote up
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 );
  }
}
 
Example 18
Source File: FieldTypeConverterProcessor.java    From datacollector with Apache License 2.0 4 votes vote down vote up
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;
  }
}
 
Example 19
Source File: DecimalFormatTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
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);
}
 
Example 20
Source File: ValueMetaBase.java    From hop with Apache License 2.0 4 votes vote down vote up
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 );
    }
  }
}