diff --git a/src/arcade/core/util/MiniBox.java b/src/arcade/core/util/MiniBox.java index aef993d7..43bcd5ee 100644 --- a/src/arcade/core/util/MiniBox.java +++ b/src/arcade/core/util/MiniBox.java @@ -67,6 +67,18 @@ public int getInt(String id) { */ public double getDouble(String id) { String s = contents.get(id); + + if (s != null && s.contains("/")) { + String[] split = s.split("/", 2); + double numerator = (!split[0].matches(NUMBER_REGEX) + ? Double.NaN + : Double.parseDouble(split[0])); + double denominator = (!split[1].matches(NUMBER_REGEX) + ? Double.NaN + : Double.parseDouble(split[1])); + return (denominator == 0 ? Double.NaN : numerator / denominator); + } + return (s == null || !s.matches(NUMBER_REGEX) ? Double.NaN : Double.parseDouble(s)); } diff --git a/test/arcade/core/util/MiniBoxTest.java b/test/arcade/core/util/MiniBoxTest.java index 49c1a6a7..a0c3ea50 100644 --- a/test/arcade/core/util/MiniBoxTest.java +++ b/test/arcade/core/util/MiniBoxTest.java @@ -114,6 +114,38 @@ public void getDouble_givenValidKeyGivenDouble_returnsValue() { } } + @Test + public void getDouble_givenValidKeyGivenValidFraction_returnsValue() { + String key = randomString(); + String[] doubles = new String[] { "1/2", "3/4", "5E-1/10" }; + double[] values = new double[] { 0.5, 0.75, 0.05 }; + for (int i = 0; i < doubles.length; i++) { + MiniBox box = new MiniBox(); + box.put(key, doubles[i]); + assertEquals(values[i], box.getDouble(key), EPSILON); + } + } + + @Test + public void getDouble_givenValidKeyGivenInvalidFraction_returnsNaN() { + String key = randomString(); + String[] doubles = new String[] { "1/2/3", "/1", "1/" }; + for (int i = 0; i < doubles.length; i++) { + MiniBox box = new MiniBox(); + box.put(key, doubles[i]); + assertTrue(Double.isNaN(box.getDouble(key))); + } + } + + @Test + public void getDouble_givenValidKeyGivenZeroFraction_returnsNaN() { + MiniBox box = new MiniBox(); + String key = randomString(); + String contents = "1/0"; + box.put(key, contents); + assertTrue(Double.isNaN(box.getDouble(key))); + } + @Test public void getDouble_givenInvalidContentsGivenString_returnsNaN() { MiniBox box = new MiniBox();