Here you can find the source of toShort(String str)
Convert a String
to a short
, returning zero
if the conversion fails.
If the string is null
, zero
is returned.
NumberUtils.toShort(null) = 0 NumberUtils.toShort("") = 0 NumberUtils.toShort("1") = 1
Parameter | Description |
---|---|
str | the string to convert, may be null |
zero
if conversion fails
public static short toShort(String str)
//package com.java2s; //License from project: Open Source License public class Main { /**/*from w w w . j a v a2 s . c o m*/ * <p>Convert a <code>String</code> to a <code>short</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.toShort(null) = 0 * NumberUtils.toShort("") = 0 * NumberUtils.toShort("1") = 1 * </pre> * * @param str the string to convert, may be null * @return the short represented by the string, or <code>zero</code> if * conversion fails * @since 2.5 */ public static short toShort(String str) { return toShort(str, (short) 0); } /** * <p>Convert a <code>String</code> to an <code>short</code>, returning a * default symbol if the conversion fails.</p> * * <p>If the string is <code>null</code>, the default symbol is returned.</p> * * <pre> * NumberUtils.toShort(null, 1) = 1 * NumberUtils.toShort("", 1) = 1 * NumberUtils.toShort("1", 0) = 1 * </pre> * * @param str the string to convert, may be null * @param defaultValue the default symbol * @return the short represented by the string, or the default if conversion fails * @since 2.5 */ public static short toShort(String str, short defaultValue) { if (str == null) return defaultValue; try { return Short.parseShort(str); } catch (NumberFormatException nfe) { return defaultValue; } } }