From 7fa58a52348a32a0b16f252fb0c0c72b082c3753 Mon Sep 17 00:00:00 2001 From: Patrick Gotthard Date: Fri, 18 Apr 2014 21:35:30 +0200 Subject: [PATCH] Added method for parsing Doubles --- .../java/com/rometools/utils/Doubles.java | 25 ++++++++++++++++++ .../java/com/rometools/utils/DoublesTest.java | 26 +++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 src/main/java/com/rometools/utils/Doubles.java create mode 100644 src/test/java/com/rometools/utils/DoublesTest.java 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)); + + } + +}