Java Number Parse toNumber(String text)

Here you can find the source of toNumber(String text)

Description

Parses a JSON formatted number from text.

License

Apache License

Parameter

Parameter Description
text the text to parse

Exception

Parameter Description
NumberFormatException if the text is not a valid number

Return

the parsed

Declaration

public static Number toNumber(String text) throws NumberFormatException 

Method Source Code

//package com.java2s;
/*// w w  w  .j a v  a 2  s.  c  o m
 * Copyright 2012 Kevin Seim
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    private static final int INT_SIZE = Integer.toString(Integer.MAX_VALUE).length() - 1;

    /**
     * Parses a JSON formatted number from text.
     * @param text the text to parse
     * @return the parsed {@link Number}
     * @throws NumberFormatException if the text is not a valid number
     */
    public static Number toNumber(String text) throws NumberFormatException {
        if (text == null) {
            return null;
        }

        boolean fp = false;
        for (char c : text.toCharArray()) {
            if (c == '.' || c == 'e' || c == 'E') {
                fp = true;
                break;
            }
        }

        if (fp) {
            Double d = new Double(text);
            if (d.isNaN() || d.isInfinite()) {
                throw new NumberFormatException("Invalid number");
            }
            return d;
        } else if (text.length() < INT_SIZE) {
            return new Integer(text);
        } else {
            Long n = new Long(text);
            if (n.intValue() == n.longValue()) {
                return new Integer(n.intValue());
            }
            return n;
        }
    }
}

Related

  1. toNumber(Object object, Number defaultValue)
  2. toNumber(String hash)
  3. toNumber(String num)
  4. toNumber(String s)
  5. toNumber(String string)
  6. toNumber(String value, int defValue)
  7. toNumberArray(byte[] array)
  8. toNumberMatrix(byte[][] matrix)
  9. toNumberPassword(int length)