Package shared.number

Source Code of shared.number.JIntegerHelper

/*
*  JIntegerHelper.java
*
*  Created on 10.09.2009, 10:53:22
*
*  Copyright (C) 10.09.2009  reiner

*  This program is free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  You should have received a copy of the GNU General Public License
*  along with this program; if not, write to the Free Software
*  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/


/**
*
* @author reiner
*/

package shared.number;

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;

/**
* Parse a integer value from a string in decimal of hexadecimal format
*/

public final class JIntegerHelper
{
    private JIntegerHelper()
    {}

    /**
     * Parse an integer in decimal and hex when prefixed with '0x'
     * @param str the string which will be parsed
     * @return returns an integer
     * @throws NumberFormatException if the string is not parsable
     */
    public static int parseIntegerHex(String str) throws NumberFormatException
    {
        str = str.trim();
        return (str.length() > 2 && str.substring(0, 2).equals("0x") ? Integer.parseInt(str.substring(2, str.length()), 16) : Integer.parseInt(str));
    }

    public static int parseInteger(String str, Locale locale) throws NumberFormatException
    {
        int val = 0;
        try
        {
            val = parseIntegerHex(str);
        }
        catch(NumberFormatException ex)
        {
            try
            {
                NumberFormat numberFormat = NumberFormat.getInstance(locale);
                val = numberFormat.parse(str).intValue();
            }
            catch(ParseException e)
            {
                throw new NumberFormatException(e.getMessage());
            }
        }
        return val;
    }

    public static int parseInteger(String str) throws NumberFormatException
    {
        return parseInteger(str, Locale.getDefault());
    }

}
TOP

Related Classes of shared.number.JIntegerHelper

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.