Skip to content

Commit 397ab37

Browse files
committed
add new number util method
1 parent a0b08f2 commit 397ab37

3 files changed

Lines changed: 30 additions & 1 deletion

File tree

build.gradle

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ buildscript {
88
}
99
}
1010

11-
rootProject.version = '9.3.0'
11+
rootProject.version = '9.4.0'
1212
group = 'com.spaceshift'
1313

1414
allprojects {

rlib-common/src/main/java/com/ss/rlib/common/util/NumberUtils.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,26 @@ public static boolean isLong(@Nullable String string) {
111111
}
112112
}
113113

114+
/**
115+
* Convert a string to int object or null if this string is null or not a number.
116+
*
117+
* @param string the string to convert.
118+
* @return the int object or null.
119+
* @since 9.4.0
120+
*/
121+
public static @Nullable Integer safeToInt(@Nullable String string) {
122+
123+
if (string == null) {
124+
return null;
125+
} else {
126+
try {
127+
return Integer.valueOf(string);
128+
} catch (NumberFormatException e) {
129+
return null;
130+
}
131+
}
132+
}
133+
114134
/**
115135
* Convert a string to long object or null if this string is null or not a number.
116136
*

rlib-common/src/test/java/com/ss/rlib/common/test/util/NumberUtilsTest.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,4 +40,13 @@ void shouldConvertStringToOptionalLong() {
4040
Assertions.assertFalse(NumberUtils.toOptionalLong(null).isPresent());
4141
Assertions.assertFalse(NumberUtils.toOptionalLong("2.1234").isPresent());
4242
}
43+
44+
@Test
45+
void shouldSafetyConvertStringToInt() {
46+
Assertions.assertNotNull(NumberUtils.safeToInt("1"));
47+
Assertions.assertNotNull(NumberUtils.safeToInt("123124"));
48+
Assertions.assertNull(NumberUtils.safeToInt("notlong"));
49+
Assertions.assertNull(NumberUtils.safeToInt(null));
50+
Assertions.assertNull(NumberUtils.safeToInt("2.1234"));
51+
}
4352
}

0 commit comments

Comments
 (0)