Added method to convert a (decimal) String to Long
This commit is contained in:
parent
90a3792ccc
commit
25abc65f91
2 changed files with 51 additions and 0 deletions
25
src/main/java/com/rometools/utils/Longs.java
Normal file
25
src/main/java/com/rometools/utils/Longs.java
Normal file
|
@ -0,0 +1,25 @@
|
||||||
|
package com.rometools.utils;
|
||||||
|
|
||||||
|
public final class Longs {
|
||||||
|
|
||||||
|
private Longs() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts a String into a Long by first parsing it as Double and then casting it to Long.
|
||||||
|
*
|
||||||
|
* @param s The String to convert, may be null or in decimal format
|
||||||
|
* @return The parsed Long or null when parsing is not possible
|
||||||
|
*/
|
||||||
|
public static Long parseDecimal(final String s) {
|
||||||
|
Long parsed = null;
|
||||||
|
try {
|
||||||
|
if (s != null) {
|
||||||
|
parsed = (long) Double.parseDouble(s);
|
||||||
|
}
|
||||||
|
} catch (final NumberFormatException e) {
|
||||||
|
}
|
||||||
|
return parsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
26
src/test/java/com/rometools/utils/LongsTest.java
Normal file
26
src/test/java/com/rometools/utils/LongsTest.java
Normal file
|
@ -0,0 +1,26 @@
|
||||||
|
package com.rometools.utils;
|
||||||
|
|
||||||
|
import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
|
import static org.hamcrest.Matchers.is;
|
||||||
|
import static org.hamcrest.Matchers.nullValue;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class LongsTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testParseDecimal() {
|
||||||
|
|
||||||
|
final String nullString = null;
|
||||||
|
final String emptyString = "";
|
||||||
|
final String longString = String.valueOf(Long.MAX_VALUE);
|
||||||
|
final String decimalString = String.valueOf(Double.MAX_VALUE);
|
||||||
|
|
||||||
|
assertThat(Longs.parseDecimal(nullString), is(nullValue()));
|
||||||
|
assertThat(Longs.parseDecimal(emptyString), is(nullValue()));
|
||||||
|
assertThat(Longs.parseDecimal(longString), is(Long.MAX_VALUE));
|
||||||
|
assertThat(Longs.parseDecimal(decimalString), is((long) Double.MAX_VALUE));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Loading…
Reference in a new issue