Example usage for java.text DecimalFormat parse

List of usage examples for java.text DecimalFormat parse

Introduction

In this page you can find the example usage for java.text DecimalFormat parse.

Prototype

public Number parse(String source) throws ParseException 

Source Link

Document

Parses text from the beginning of the given string to produce a number.

Usage

From source file:com.qcadoo.mes.operationTimeCalculations.OrderRealizationTimeServiceImpl.java

@Override
public BigDecimal getBigDecimalFromField(final Object value, final Locale locale) {
    try {//www .  j  a v  a 2 s .  c o m
        DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(locale);
        format.setParseBigDecimal(true);
        return new BigDecimal(format.parse(value.toString()).doubleValue());
    } catch (ParseException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:edu.ucla.stat.SOCR.chart.demo.EventFrequencyDemo1.java

public void resetExample() {

    dataset = createDataset(true);/*from  w  w  w  . j  av a2s  . co m*/

    JFreeChart chart = createChart(dataset);
    chartPanel = new ChartPanel(chart, false);

    //      setSummary(dataset);
    setChart();

    hasExample = true;
    convertor.dataset2Table(dataset);
    JTable tempDataTable = convertor.getTable();
    resetTableRows(tempDataTable.getRowCount() + 1);
    resetTableColumns(tempDataTable.getColumnCount() + 1);

    for (int i = 0; i < tempDataTable.getColumnCount(); i++) {
        columnModel.getColumn(i).setHeaderValue(tempDataTable.getColumnName(i));
        //  System.out.println("updateExample tempDataTable["+i+"] = " +tempDataTable.getColumnName(i));
    }

    columnModel = dataTable.getColumnModel();
    dataTable.setTableHeader(new EditableHeader(columnModel));

    DecimalFormat f = new DecimalFormat("#.#E0");
    for (int i = 0; i < tempDataTable.getRowCount(); i++)
        for (int j = 0; j < tempDataTable.getColumnCount(); j++) {
            if (j != 0) {
                try {
                    long time = f.parse((String) tempDataTable.getValueAt(i, j)).longValue();
                    Date date = new Date(time);
                    dataTable.setValueAt(new Day(date).toString(), i, j);
                } catch (ParseException e) {
                    dataTable.setValueAt("NaN", i, j);
                }
            } else
                dataTable.setValueAt(tempDataTable.getValueAt(i, j), i, j);
        }
    dataPanel.removeAll();
    dataPanel.add(new JScrollPane(dataTable));
    dataTable.setGridColor(Color.gray);
    dataTable.setShowGrid(true);
    dataTable.doLayout();
    // this is a fix for the BAD SGI Java VM - not up to date as of dec. 22, 2003
    try {
        dataTable.setDragEnabled(true);
    } catch (Exception e) {
    }

    dataPanel.validate();

    // do the mapping
    addButtonDependent();
    int columnCount = dataset.getColumnCount();
    for (int i = 0; i < columnCount; i++)
        addButtonIndependent();

    updateStatus(url);
}

From source file:org.openadaptor.auxil.connector.iostream.writer.FileWriteConnector.java

/**
 * attempts to retrieve a valid number from the supplied string. This
 * number is then multiplied by the mupltiplier to convert it into
 * milliseconds and used for the rollover period. If the string does
 * not fit the format then we simply leave the rollover period as it
 * was and return.//ww  w . j  a va2 s  . c  om
 *
 * @param s - the string to be converted
 * @param indicater - the rollover period indicater (eg. M, W, D, ...)
 * @param multiplier - the value to multiply the rollover period by to
 * convert to milliseconds (eg. 2D becomes 2*24*60*60*1000)
 */
private void parseDate(String s, String indicater, long multiplier) {
    try {
        DecimalFormat nf = new DecimalFormat("#" + indicater);
        Number n = nf.parse(s.toLowerCase());

        rolloverPeriod = n.longValue() * multiplier;
    } catch (ParseException e) {
    }
}

From source file:org.ohmage.domain.campaign.prompt.BoundedPrompt.java

/**
 * Verifies that the value of the condition is not outside the bounds of
 * the prompt.//  w  w  w.  j  av a2 s  . co m
 * 
 * @param pair The condition-value pair to validate.
 * 
 * @throws DomainException The value was not a number or was outside the
 *                      predefined bounds.
 */
@Override
public void validateConditionValuePair(final ConditionValuePair pair) throws DomainException {

    try {
        DecimalFormat decimalFormat = new DecimalFormat();
        decimalFormat.setParseBigDecimal(true);
        BigDecimal value = (BigDecimal) decimalFormat.parse(pair.getValue());

        // Verify that the default is not less than the minimum.
        if (value.compareTo(getMin()) < 0) {
            throw new DomainException("The value of the condition is less than the " + "minimum allowed value ("
                    + getMin() + "): " + pair.getValue());
        }
        // Verify that the default is not greater than the maximum.
        else if (value.compareTo(getMax()) > 0) {
            throw new DomainException("The value of the condition is greater than the "
                    + "maximum allowed value (" + getMax() + "): " + pair.getValue());
        }
        // Verify that the condition is a whole number if the response
        // must be a whole number
        else if (mustBeWholeNumber() && !isWholeNumber(value)) {
            throw new DomainException("The value of the condition is a decimal, but the "
                    + "flag indicatest that only whole numbers are " + "possible.");
        }
    } catch (ParseException e) {
        throw new DomainException("The value of the condition is not a number: " + pair.getValue(), e);
    }
}

From source file:org.openadaptor.auxil.connector.iostream.writer.FileWriteConnector.java

/**
 * attempts to retrieve a valid number from the supplied string. This
 * number is then multiplied by the mupltiplier and used for the
 * rollover size. If the string does not fit the format then we simply
 * leave the rollover size as it was and return.
 *
 * @param s - the string to be converted
 * @param indicater - the file size indicater (eg. Gb, Mb, Kb, ...)
 * @param multiplier - the value to multiply the rollover size by to
 * convert to bytes (eg. 2Kb becomes 2000)
 *//* w  w  w .ja  va  2 s  .c  om*/
private void parseSize(String s, String indicater, int multiplier) {
    try {
        DecimalFormat nf = new DecimalFormat("#,##0" + indicater);
        Number n = nf.parse(s.toLowerCase());

        rolloverSize = n.longValue() * multiplier;
    } catch (ParseException e) {
    }
}

From source file:br.msf.commons.util.CharSequenceUtils.java

public static boolean isNumber(final CharSequence sequence, final Locale locale) {
    if (sequence == null) {
        return false;
    }//from   w ww  .  j a  v a 2  s  . com
    try {
        DecimalFormat formater = (DecimalFormat) DecimalFormat
                .getInstance(LocaleUtils.getNullSafeLocale(locale));
        formater.setParseBigDecimal(true);
        formater.parse(sequence.toString());
        return true;
    } catch (ParseException ex) {
        return false;
    }
}

From source file:org.talend.dataprep.api.dataset.RowMetadata.java

private ColumnMetadata addColumn(ColumnMetadata columnMetadata, int index) {
    String columnIdFromMetadata = columnMetadata.getId();
    DecimalFormat columnIdFormat = new DecimalFormat(COLUMN_ID_PATTERN);
    if (StringUtils.isBlank(columnIdFromMetadata)) {
        columnMetadata.setId(columnIdFormat.format(nextId));
        nextId++;/* www  .j av  a 2  s .  com*/
    } else {
        try {
            int columnId = columnIdFormat.parse(columnIdFromMetadata).intValue();
            int possibleNextId = columnId + 1;
            if (possibleNextId > nextId) {
                nextId = possibleNextId;
            }
        } catch (ParseException e) {
            LOGGER.error("Unable to parse column id from metadata '" + columnIdFromMetadata + "'", e);
        }
    }
    columns.add(index, columnMetadata);
    return columnMetadata;
}

From source file:org.ohmage.domain.campaign.prompt.BoundedPrompt.java

/**
 * Validates that a given value is valid and, if so, converts it into an 
 * appropriate object./*from   www  .  j av a  2 s.  co  m*/
 * 
 * @param value The value to be validated. This must be one of the  
 *             following:<br />
 *             <ul>
 *             <li>{@link NoResponse}</li>
 *             <li>{@link AtomicInteger}</li>
 *             <li>{@link AtomicLong}</li>
 *             <li>{@link BigInteger}</li>
 *             <li>{@link Integer}</li>
 *             <li>{@link Long}</li>
 *             <li>{@link Short}</li>
 *             <li>{@link String} that represents:</li>
 *               <ul>
 *                 <li>{@link NoResponse}</li>
 *                 <li>A whole number.</li>
 *               <ul>
 *             </ul>
 * 
 * @return A {@link Number} object or a {@link NoResponse} object.
 * 
 * @throws DomainException The value is invalid.
 */
@Override
public Object validateValue(final Object value) throws DomainException {
    BigDecimal result;

    // If it's already a NoResponse value, then return make sure that if it
    // was skipped that it as skippable.
    if (value instanceof NoResponse) {
        if (NoResponse.SKIPPED.equals(value) && (!skippable())) {
            throw new DomainException("The prompt, '" + getId() + "', was skipped, but it is not skippable.");
        }

        return value;
    }
    // If it's already a number, be sure it is a whole number, if required.
    else if (value instanceof Number) {
        result = new BigDecimal(value.toString());
        if (mustBeWholeNumber() && (!isWholeNumber(result))) {
            throw new DomainException("The value cannot be a decimal: " + value);
        }
    }
    // If it is a string, parse it to check if it's a NoResponse value and,
    // if not, parse it as a long. If that does not work either, throw an
    // exception.
    else if (value instanceof String) {
        String stringValue = (String) value;

        try {
            //throw new NoResponseException(NoResponse.valueOf(stringValue));
            return NoResponse.valueOf(stringValue);
        } catch (IllegalArgumentException iae) {
            // Parse it.
            try {
                DecimalFormat format = new DecimalFormat();
                format.setParseBigDecimal(true);
                result = (BigDecimal) format.parse(stringValue);
            } catch (ParseException e) {
                throw new DomainException("The value could not be decoded as a number: " + stringValue, e);
            }
        }

        // Validate it.
        if (mustBeWholeNumber() && (!isWholeNumber(result))) {
            throw new DomainException("The value cannot be a decimal: " + value);
        }
    }
    // Finally, if its type is unknown, throw an exception.
    else {
        throw new DomainException(
                "The value is not decodable as a response value for " + "prompt '" + getId() + "'.");
    }

    // Now that we have a Number value, verify that it is within bounds.
    if (min.compareTo(result) > 0) {
        throw new DomainException("The value is less than the lower bound (" + min + ") for the prompt, '"
                + getId() + "': " + result);
    } else if (max.compareTo(result) < 0) {
        throw new DomainException("The value is greater than the upper bound (" + max + ") for the prompt, '"
                + getId() + "': " + result);
    }

    return result;
}

From source file:com.joliciel.jochre.search.highlight.HighlightTerm.java

public void toJson(JsonGenerator jsonGen, DecimalFormat df) {
    try {/* w w w .  j  a  v  a2s  .c om*/
        jsonGen.writeStartObject();
        jsonGen.writeStringField("field", this.getField());
        jsonGen.writeNumberField("start", this.getStartOffset());
        jsonGen.writeNumberField("end", this.getEndOffset());
        jsonGen.writeNumberField("pageIndex", this.getPageIndex());
        jsonGen.writeNumberField("imageIndex", this.getImageIndex());
        double roundedWeight = df.parse(df.format(this.getWeight())).doubleValue();
        jsonGen.writeNumberField("weight", roundedWeight);
        jsonGen.writeEndObject();

        jsonGen.flush();
    } catch (java.text.ParseException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    } catch (IOException ioe) {
        LogUtils.logError(LOG, ioe);
        throw new RuntimeException(ioe);
    }
}

From source file:com.joliciel.jochre.search.highlight.Snippet.java

public void toJson(JsonGenerator jsonGen, DecimalFormat df) {
    try {/*w  w  w .j a v a  2 s .  c  om*/
        jsonGen.writeStartObject();
        jsonGen.writeNumberField("docId", docId);
        jsonGen.writeStringField("field", this.getField());
        jsonGen.writeNumberField("start", this.getStartOffset());
        jsonGen.writeNumberField("end", this.getEndOffset());
        double roundedScore = df.parse(df.format(this.getScore())).doubleValue();
        jsonGen.writeNumberField("score", roundedScore);
        jsonGen.writeArrayFieldStart("terms");
        for (HighlightTerm term : this.getHighlightTerms()) {
            term.toJson(jsonGen, df);
        }
        jsonGen.writeEndArray(); // terms

        jsonGen.writeEndObject();
        jsonGen.flush();
    } catch (java.text.ParseException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    } catch (IOException ioe) {
        LogUtils.logError(LOG, ioe);
        throw new RuntimeException(ioe);
    }
}