KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > util > StringConvert


1 package jodd.util;
2
3 /**
4  * Converts Strings to various primitives. Strings are used very often for
5  * holding numbers. This class simplifies converting strings to numbers,
6  * without need of exception handling.
7  */

8 public final class StringConvert {
9
10     /**
11      * Converts String to float.
12      *
13      * @param value
14      * @param defaultValue
15      *
16      * @return converted value, or default value if error
17      */

18     public static float toFloat(String value, float defaultValue) {
19         if (value == null) {
20             return defaultValue;
21         }
22         try {
23             return Float.parseFloat(value);
24         } catch (NumberFormatException nfex) {
25             return defaultValue;
26         }
27     }
28
29     /**
30      * Converts String to double.
31      *
32      * @param value
33      * @param defaultValue
34      *
35      * @return converted value, or default value if error
36      */

37     public static double toDouble(String value, double defaultValue) {
38         if (value == null) {
39             return defaultValue;
40         }
41         try {
42             return Double.parseDouble(value);
43         } catch (NumberFormatException nfex) {
44             return defaultValue;
45         }
46     }
47
48     /**
49      * Converts String to int.
50      *
51      * @param value
52      * @param defaultValue
53      *
54      * @return converted value, or default value if error
55      */

56     public static int toInt(String value, int defaultValue) {
57         if (value == null) {
58             return defaultValue;
59         }
60         try {
61             return Integer.parseInt(value);
62         } catch (NumberFormatException nfex) {
63             return defaultValue;
64         }
65     }
66
67     /**
68      * Converts String to long.
69      *
70      * @param value
71      * @param defaultValue
72      *
73      * @return converted value, or default value if error
74      */

75     public static long toLong(String value, long defaultValue) {
76         if (value == null) {
77             return defaultValue;
78         }
79         try {
80             return Long.parseLong(value);
81         } catch (NumberFormatException nfex) {
82             return defaultValue;
83         }
84     }
85
86     /**
87      * Converts String to byte.
88      *
89      * @param value
90      * @param defaultValue
91      *
92      * @return converted value, or default value if error
93      */

94     public static byte toByte(String value, byte defaultValue) {
95         if (value == null) {
96             return defaultValue;
97         }
98         try {
99             return Byte.parseByte(value);
100         } catch (NumberFormatException nfex) {
101             return defaultValue;
102         }
103     }
104
105
106 }
107
Popular Tags