Example usage for java.text NumberFormat setParseIntegerOnly

List of usage examples for java.text NumberFormat setParseIntegerOnly

Introduction

In this page you can find the example usage for java.text NumberFormat setParseIntegerOnly.

Prototype

public void setParseIntegerOnly(boolean value) 

Source Link

Document

Sets whether or not numbers should be parsed as integers only.

Usage

From source file:org.openestate.io.core.NumberUtils.java

/**
 * Convert a string value into a number.
 *
 * @param value/*from   www .  j a  va 2s.  c o m*/
 * the string value to convert
 *
 * @param integerOnly
 * wether only the integer part of the value is parsed
 *
 * @param locales
 * locales, against which the value is parsed
 *
 * @return
 * numeric value for the string
 *
 * @throws NumberFormatException
 * if the string is not a valid number
 */
public static Number parseNumber(String value, boolean integerOnly, Locale... locales)
        throws NumberFormatException {
    value = StringUtils.trimToNull(value);
    if (value == null)
        return null;

    // ignore leading plus sign
    if (value.startsWith("+"))
        value = StringUtils.trimToNull(value.substring(1));

    // remove any spaces
    value = StringUtils.replace(value, StringUtils.SPACE, StringUtils.EMPTY);

    if (ArrayUtils.isEmpty(locales))
        locales = new Locale[] { Locale.getDefault() };

    for (Locale locale : locales) {
        // check, if the value is completely numeric for the locale
        if (!isNumeric(value, locale))
            continue;
        try {
            NumberFormat format = NumberFormat.getNumberInstance(locale);
            format.setMinimumFractionDigits(0);
            format.setGroupingUsed(false);
            format.setParseIntegerOnly(integerOnly);
            return format.parse(value);
        } catch (ParseException ex) {
        }
    }
    throw new NumberFormatException("The provided value '" + value + "' is not numeric!");
}