diff --git a/src/main/java/com/rometools/utils/Doubles.java b/src/main/java/com/rometools/utils/Doubles.java new file mode 100644 index 0000000..c3cf6da --- /dev/null +++ b/src/main/java/com/rometools/utils/Doubles.java @@ -0,0 +1,25 @@ +package com.rometools.utils; + +public class Doubles { + + private Doubles() { + } + + /** + * Converts a String into an Double. + * + * @param s The String to convert, may be null + * @return The parsed Double or null when parsing is not possible + */ + public static Double parse(final String s) { + Double parsed = null; + try { + if (s != null) { + parsed = Double.parseDouble(s); + } + } catch (final NumberFormatException e) { + } + return parsed; + } + +} diff --git a/src/test/java/com/rometools/utils/DoublesTest.java b/src/test/java/com/rometools/utils/DoublesTest.java new file mode 100644 index 0000000..f688d80 --- /dev/null +++ b/src/test/java/com/rometools/utils/DoublesTest.java @@ -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 DoublesTest { + + @Test + public void testParse() { + + final String nullString = null; + final String emptyString = null; + final String integerString = "1"; + final String decimalString = "1.0"; + + assertThat(Doubles.parse(nullString), is(nullValue())); + assertThat(Doubles.parse(emptyString), is(nullValue())); + assertThat(Doubles.parse(integerString), is(1.0)); + assertThat(Doubles.parse(decimalString), is(1.0)); + + } + +}