Here you can find the source of toLong(String str)
Convert a String
to a long
, returning zero
if the conversion fails.
Parameter | Description |
---|---|
str | the string to convert, may be null |
0
if conversion fails
public static long toLong(String str)
//package com.java2s; /*//from w ww . j a va 2s. c o m * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 { /** * <p> * Convert a <code>String</code> to a <code>long</code>, returning <code>zero</code> if the conversion fails. * </p> * * <p> * If the string is <code>null</code>, <code>zero</code> is returned. * </p> * * <pre> * NumberUtils.toLong(null) = 0L * NumberUtils.toLong("") = 0L * NumberUtils.toLong("1") = 1L * </pre> * * @param str * the string to convert, may be null * @return the long represented by the string, or <code>0</code> if conversion fails * @since 2.1 */ public static long toLong(String str) { return toLong(str, 0L); } /** * <p> * Convert a <code>String</code> to a <code>long</code>, returning a default value if the conversion fails. * </p> * * <p> * If the string is <code>null</code>, the default value is returned. * </p> * * <pre> * NumberUtils.toLong(null, 1L) = 1L * NumberUtils.toLong("", 1L) = 1L * NumberUtils.toLong("1", 0L) = 1L * </pre> * * @param str * the string to convert, may be null * @param defaultValue * the default value * @return the long represented by the string, or the default if conversion fails * @since 2.1 */ public static long toLong(String str, long defaultValue) { if (str == null) { return defaultValue; } try { return Long.parseLong(str); } catch (NumberFormatException nfe) { return defaultValue; } } }