Example usage for java.text NumberFormat parse

List of usage examples for java.text NumberFormat parse

Introduction

In this page you can find the example usage for java.text NumberFormat 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:org.projectforge.common.NumberHelper.java

/**
 *//*from  w ww .  j  a va 2 s .  com*/
public static BigDecimal parseCurrency(String value, final Locale locale) {
    if (value == null) {
        return null;
    }
    value = value.trim();
    if (value.length() == 0) {
        return null;
    }
    final NumberFormat format = getCurrencyFormat(locale);
    BigDecimal result = null;
    try {
        final Number number = format.parse(value);
        if (number != null) {
            result = new BigDecimal(number.toString());
            result = result.setScale(2, BigDecimal.ROUND_HALF_UP);
        }
    } catch (final ParseException ex) {
        log.debug(ex.getMessage(), ex);
    }
    return result;
}

From source file:funcoes.funcoes.java

public static String formatoParaInserir(String valor) throws ParseException {

    NumberFormat formato2 = NumberFormat.getNumberInstance();
    return formato2.parse(valor).toString();

}

From source file:com.jbombardier.reports.ReportGenerator.java

private static void generatePathView(File folder, String phase, String distinctPath,
        List<CapturedStatistic> capturedStatistics) {

    HTMLBuilder2 builder = new HTMLBuilder2();

    builder.getHead().css("box.css");
    builder.getHead().css("table.css");

    HTMLBuilder2.Element bodyx = builder.getBody();

    final HTMLBuilder2.Element content = bodyx.div("wide-box");

    TimeSeries series = new TimeSeries(distinctPath);
    TimeSeriesCollection data = new TimeSeriesCollection();
    data.addSeries(series);//from   w w  w  . ja va  2s.  co  m

    NumberFormat nf = NumberFormat.getInstance();

    try {
        for (CapturedStatistic capturedStatistic : capturedStatistics) {
            if (capturedStatistic.getPath().equals(distinctPath)) {
                series.addOrUpdate(new Second(new Date(capturedStatistic.getTime())),
                        nf.parse(capturedStatistic.getValue()));
            }
        }
    } catch (ParseException nfe) {
        // Skip this one, its not numeric
    }

    if (series.getItemCount() > 0) {
        final String imageName = StringUtils.format("phase-{}-path-{}.png", phase,
                distinctPath.replace('/', '-'));
        content.image(imageName);

        final File file = new File(folder, imageName);
        render(StringUtils.format("phase-{}-path-{}.html", phase, distinctPath.replace('/', '-')), data, file);
    }

    builder.toFile(new File(folder,
            StringUtils.format("phase-{}-path-{}.html", phase, distinctPath.replace('/', '-'))));

}

From source file:com.xumpy.thuisadmin.services.implementations.BedragenSrvImpl.java

public static BigDecimal convertComma(String bedrag) {
    if (bedrag.contains(",")) {
        bedrag = bedrag.replace(".", "");
        bedrag = bedrag.replace(",", ".");
    } else {//from w ww.  j a v a2  s . c  o m
        if (bedrag.indexOf(".", bedrag.indexOf(".") + 1) != -1) {
            bedrag = bedrag.replace(".", "");
        }
    }

    NumberFormat nf = NumberFormat.getInstance(new Locale("US"));
    BigDecimal bigDecimalBedrag = new BigDecimal(0);
    try {
        bigDecimalBedrag = new BigDecimal(nf.parse(bedrag).doubleValue());
    } catch (ParseException ex) {
        Logger.getLogger(BedragenSrvImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
    bigDecimalBedrag = bigDecimalBedrag.setScale(2, BigDecimal.ROUND_HALF_UP);

    return bigDecimalBedrag;
}

From source file:com.mgmtp.perfload.perfalyzer.util.PerfAlyzerUtils.java

/**
 * Reads a semicolon-delimited CSV file into a list. Each line in the result list will be
 * another list of {@link Number} objects. The file is expected to have two numberic columns
 * which are parsed using the specified number format.
 * //  w  w  w  . j  ava  2 s . c  o m
 * @param file
 *            the file
 * @param charset
 *            the character set to read the file
 * @param numberFormat
 *            the number format for parsing the column values
 * @return the immutable result list
 */
public static List<SeriesPoint> readDataFile(final File file, final Charset charset,
        final NumberFormat numberFormat) throws IOException {
    final StrTokenizer tokenizer = StrTokenizer.getCSVInstance();
    tokenizer.setDelimiterChar(';');

    try (BufferedReader br = newReader(file, charset)) {
        boolean headerLine = true;
        List<SeriesPoint> result = newArrayListWithExpectedSize(200);

        for (String line; (line = br.readLine()) != null;) {
            try {
                if (headerLine) {
                    headerLine = false;
                } else {
                    tokenizer.reset(line);
                    String[] tokens = tokenizer.getTokenArray();
                    double x = numberFormat.parse(tokens[0]).doubleValue();
                    double y = numberFormat.parse(tokens[1]).doubleValue();

                    if (!result.isEmpty()) {
                        // additional point for histogram
                        SeriesPoint previousPoint = getLast(result);
                        result.add(new SeriesPoint(x, previousPoint.getY()));
                    }
                    tokenizer.reset(line);
                    result.add(new SeriesPoint(x, y));
                }
            } catch (ParseException ex) {
                throw new IOException("Error parsing number in file: " + file, ex);
            }
        }

        int size = result.size();
        if (size > 2) {
            // additional point at end for histogram
            SeriesPoint nextToLast = result.get(size - 3);
            SeriesPoint last = result.get(size - 1);
            double dX = last.getX().doubleValue() - nextToLast.getX().doubleValue();
            result.add(new SeriesPoint(last.getX().doubleValue() + dX, last.getY()));
        }
        return ImmutableList.copyOf(result);
    }
}

From source file:org.crazydog.util.spring.NumberUtils.java

/**
 * Parse the given text into a number instance of the given target class,
 * using the given NumberFormat. Trims the input {@code String}
 * before attempting to parse the number.
 *
 * @param text         the text to convert
 * @param targetClass  the target class to parse into
 * @param numberFormat the NumberFormat to use for parsing (if {@code null},
 *                     this method falls back to {@code parseNumber(String, Class)})
 * @return the parsed number// w w  w.ja v  a2 s  .  c o m
 * @throws IllegalArgumentException if the target class is not supported
 *                                  (i.e. not a standard Number subclass as included in the JDK)
 * @see NumberFormat#parse
 * @see #convertNumberToTargetClass
 * @see #parseNumber(String, Class)
 */
public static <T extends Number> T parseNumber(String text, Class<T> targetClass, NumberFormat numberFormat) {
    if (numberFormat != null) {
        org.springframework.util.Assert.notNull(text, "Text must not be null");
        org.springframework.util.Assert.notNull(targetClass, "Target class must not be null");
        DecimalFormat decimalFormat = null;
        boolean resetBigDecimal = false;
        if (numberFormat instanceof DecimalFormat) {
            decimalFormat = (DecimalFormat) numberFormat;
            if (BigDecimal.class == targetClass && !decimalFormat.isParseBigDecimal()) {
                decimalFormat.setParseBigDecimal(true);
                resetBigDecimal = true;
            }
        }
        try {
            Number number = numberFormat.parse(StringUtils.trimAllWhitespace(text));
            return convertNumberToTargetClass(number, targetClass);
        } catch (ParseException ex) {
            throw new IllegalArgumentException("Could not parse number: " + ex.getMessage());
        } finally {
            if (resetBigDecimal) {
                decimalFormat.setParseBigDecimal(false);
            }
        }
    } else {
        return parseNumber(text, targetClass);
    }
}

From source file:org.thymeleaf.engine21.conversion.conversion3.LongFormatter.java

public Long parse(final String text, final Locale locale) throws ParseException {
    final NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US);
    return Long.valueOf(numberFormat.parse(text).longValue());
}

From source file:de.perdian.commons.lang.conversion.impl.converters.StringToNumberConverter.java

@Override
protected Number convertUsingFormat(NumberFormat format, String source) {
    try {/*w w  w.ja v a2s  . c o m*/
        return source == null ? null : format.parse(source);
    } catch (ParseException e) {
        StringBuilder errorMessage = new StringBuilder();
        errorMessage.append("Cannot parse value '").append(source).append("' into ");
        errorMessage.append(" valid Number using format '").append(format);
        errorMessage.append("'");
        throw new ConverterException(source, errorMessage.toString());
    }
}

From source file:com.bdaum.zoom.gps.internal.GpsUtilities.java

public static void getGeoAreas(IPreferenceStore preferenceStore, Collection<GeoArea> areas) {
    NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
    nf.setMaximumFractionDigits(8);/*from  www .  j  av  a 2 s. com*/
    nf.setGroupingUsed(false);
    String nogo = preferenceStore.getString(PreferenceConstants.NOGO);
    if (nogo != null) {
        int i = 0;
        double lat = 0, lon = 0, km = 0;
        String name = null;
        StringTokenizer st = new StringTokenizer(nogo, ";,", true); //$NON-NLS-1$
        while (st.hasMoreTokens()) {
            String s = st.nextToken();
            if (";".equals(s)) { //$NON-NLS-1$
                areas.add(new GeoArea(name, lat, lon, km));
                i = 0;
            } else if (",".equals(s)) //$NON-NLS-1$
                ++i;
            else
                try {
                    switch (i) {
                    case 0:
                        name = s;
                        break;
                    case 1:
                        lat = nf.parse(s).doubleValue();
                        break;
                    case 2:
                        lon = nf.parse(s).doubleValue();
                        break;
                    case 3:
                        km = nf.parse(s).doubleValue();
                        break;
                    }
                } catch (ParseException e) {
                    // do nothing
                }
        }
    }
}

From source file:au.com.onegeek.lambda.core.provider.WebDriverBackedSeleniumProvider.java

public void sleep(String wait) throws InterruptedException, ParseException {
    NumberFormat format = NumberFormat.getInstance(Locale.ENGLISH);
    Number number = format.parse(wait);
    this.sleep(number.intValue());
}