Java Primitive Type Create toPrimitiveNumber(String s)

Here you can find the source of toPrimitiveNumber(String s)

Description

Converts a string into its "closest" primitive type.

License

Open Source License

Parameter

Parameter Description
s The string to convert into a number

Return

The number

Declaration

public static Number toPrimitiveNumber(String s) 

Method Source Code

//package com.java2s;
/*//from  w  w  w  . ja v  a 2 s . c  om
  LabPal, a versatile environment for running experiments on a computer
  Copyright (C) 2015-2017 Sylvain Hall?
    
  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 3 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, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    /**
     * Converts a string into its "closest" primitive type. If the
     * string parses as an integer, the number returned will be an
     * {@code int}. Otherwise, if it parses as a float, the number
     * returned will be a {@code float}. In all other cases, the
     * returned value is {@code null}.
     * @param s The string to convert into a number
     * @return The number
     */
    public static Number toPrimitiveNumber(String s) {
        if (s == null) {
            return null;
        }
        s = s.trim();
        try {
            int i = Integer.parseInt(s);
            return i;
        } catch (NumberFormatException nfe) {
            // Do nothing
        }
        try {
            float f = Float.parseFloat(s);
            return f;
        } catch (NumberFormatException nfe) {
            // Do nothing
        }
        return null;
    }
}

Related

  1. toPrimitiveByteArray(Integer[] array)
  2. toPrimitiveClass(Class wrapperClass)
  3. toPrimitiveDouble(Double d)
  4. toPrimitiveInt(Integer value)
  5. toPrimitiveInt(Object o)
  6. toPrimitiveType(Class c)
  7. toPrimitiveType(Class cls)
  8. toPrimitiveType(Class type)
  9. toPrimitiveWrapper(Class type)