Java Long Number Create toLong(Object object, long defaultValue)

Here you can find the source of toLong(Object object, long defaultValue)

Description

Extract the value represented by the given object (Number or String).

License

Open Source License

Parameter

Parameter Description
object the object to extract value from
defaultValue default value to be returned if object is null or NumberFormatException .

Return

the value extracted or default value if failed to extract the value.

Declaration

public static long toLong(Object object, long defaultValue) 

Method Source Code

//package com.java2s;
/**********************************************************************************************
 *
 * Asprise Scanning and Imaging API//from ww  w. j  a va  2  s  . c om
 * Copyright (C) 1998-2016. Asprise Inc. <asprise.com>
 *
 * This file is licensed under the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation.
 *
 * 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.
 *
 * You should have received a copy of the GNU Affero General Public License.  If not, please
 * visit <http://www.gnu.org/licenses/agpl-3.0.html>.
 *
 **********************************************************************************************/

public class Main {
    /**
     * Extract the value represented by the given object (Number or String).
     * @param object the object to extract value from
     * @param defaultValue default value to be returned if object is null or {@linkplain NumberFormatException}.
     * @return the value extracted or default value if failed to extract the value.
     */
    public static long toLong(Object object, long defaultValue) {
        if (object == null) {
            return defaultValue;
        }
        if (object instanceof Number) {
            return ((Number) object).longValue();
        }

        try {
            Double value = Double.valueOf(object.toString().trim());
            return value.longValue();
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    /**
     * Return null if object is null otherwise object.toString().
     * @param object
     * @return
     */
    public static String toString(Object object) {
        return object == null ? null : object.toString();
    }
}

Related

  1. toLong(Object obj, String pattern)
  2. toLong(Object object)
  3. toLong(Object object)
  4. toLong(Object object)
  5. toLong(Object object)
  6. toLong(Object object, Long defaultValue)
  7. toLong(Object objectToConvert)
  8. toLong(Object objValue)
  9. toLong(Object oid)