From 25abc65f91a213c4b103b6d71d35e99fde1f10ca Mon Sep 17 00:00:00 2001 From: Patrick Gotthard Date: Fri, 18 Apr 2014 20:52:04 +0200 Subject: [PATCH] Added method to convert a (decimal) String to Long --- src/main/java/com/rometools/utils/Longs.java | 25 ++++++++++++++++++ .../java/com/rometools/utils/LongsTest.java | 26 +++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 src/main/java/com/rometools/utils/Longs.java create mode 100644 src/test/java/com/rometools/utils/LongsTest.java diff --git a/src/main/java/com/rometools/utils/Longs.java b/src/main/java/com/rometools/utils/Longs.java new file mode 100644 index 0000000..8a8ce02 --- /dev/null +++ b/src/main/java/com/rometools/utils/Longs.java @@ -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; + } + +} diff --git a/src/test/java/com/rometools/utils/LongsTest.java b/src/test/java/com/rometools/utils/LongsTest.java new file mode 100644 index 0000000..79100cb --- /dev/null +++ b/src/test/java/com/rometools/utils/LongsTest.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 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)); + + } + +}