Here you can find the source of toInt(String str)
Convert a String
to an int
, returning zero
if the conversion fails.
If the string is null
, zero
is returned.
NumberUtils.toInt(null) = 0 NumberUtils.toInt("") = 0 NumberUtils.toInt("1") = 1
Parameter | Description |
---|---|
str | the string to convert, may be null |
zero
if conversion fails
public static int toInt(String str)
//package com.java2s; /*//from w ww .j a v a 2 s . co 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 an <code>int</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.toInt(null, 1) = 1 * NumberUtils.toInt("", 1) = 1 * NumberUtils.toInt("1", 0) = 1 * </pre> * * @param str the string to convert, may be null * @param defaultValue the default value * @return the int represented by the string, or the default if conversion fails * @since 2.1 */ public static int toInt(String str, int defaultValue) { if (str == null) { return defaultValue; } try { return Integer.parseInt(str); } catch (NumberFormatException nfe) { return defaultValue; } } /** * <p>Convert a <code>String</code> to an <code>int</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.toInt(null) = 0 * NumberUtils.toInt("") = 0 * NumberUtils.toInt("1") = 1 * </pre> * * @param str the string to convert, may be null * @return the int represented by the string, or <code>zero</code> if * conversion fails * @since 2.1 */ public static int toInt(String str) { return toInt(str, 0); } }