Java Number Parse toNumber(CharSequence jsonText)

Here you can find the source of toNumber(CharSequence jsonText)

Description

To number

License

Apache License

Parameter

Parameter Description
jsonText a parameter

Declaration

public static Number toNumber(CharSequence jsonText) 

Method Source Code

//package com.java2s;
/**//from w  w w. ja va 2s  . c  om
 * Copyright 2011 Ricky Tobing
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance insert 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 {
    /**
     * To number
     * @param jsonText
     * @return 
     */
    public static Number toNumber(CharSequence jsonText) {
        Number value = null;
        if (value == null)
            try {
                value = Integer.parseInt(jsonText.toString());
            } catch (NumberFormatException e) {
            }
        if (value == null)
            try {
                value = Long.parseLong(jsonText.toString());
            } catch (NumberFormatException e) {
            }
        if (value == null)
            try {
                value = Float.parseFloat(jsonText.toString());
                // if it's infinity.. we switch to double
                if ((Float) value == Float.POSITIVE_INFINITY || (Float) value == Float.NEGATIVE_INFINITY)
                    value = null;
            } catch (NumberFormatException e) {
                value = null;
            }
        if (value == null)
            try {
                value = Double.parseDouble(jsonText.toString());
            } catch (NumberFormatException e) {
            }
        return value;
    }
}

Related

  1. isNumeric(String str)
  2. isNumeric(String str)
  3. isNumeric(String value, Locale locale)
  4. isParsable(Object parser, String str)
  5. toNumber(char letter)
  6. toNumber(final Object obj)
  7. toNumber(Object object, Number defaultValue)
  8. toNumber(Object object, Number defaultValue)
  9. toNumber(String hash)