You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by er...@apache.org on 2019/02/27 00:14:22 UTC
[commons-numbers] branch fraction-dev updated: NUMBERS-74: added
parse() method to Fraction
This is an automated email from the ASF dual-hosted git repository.
ericbarnhill pushed a commit to branch fraction-dev
in repository https://gitbox.apache.org/repos/asf/commons-numbers.git
The following commit(s) were added to refs/heads/fraction-dev by this push:
new 9a4792c NUMBERS-74: added parse() method to Fraction
9a4792c is described below
commit 9a4792cc1cd265d12dde033ac818ef3dea5de816
Author: Eric Barnhill <er...@protonmail.ch>
AuthorDate: Tue Feb 26 16:14:16 2019 -0800
NUMBERS-74: added parse() method to Fraction
---
.../apache/commons/numbers/fraction/Fraction.java | 24 ++++++++++++++++++++++
1 file changed, 24 insertions(+)
diff --git a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java
index 2ec1559..0e3d76f 100644
--- a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java
+++ b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java
@@ -17,6 +17,7 @@
package org.apache.commons.numbers.fraction;
import java.io.Serializable;
+
import org.apache.commons.numbers.core.ArithmeticUtils;
import org.apache.commons.numbers.core.NativeOperators;
@@ -630,4 +631,27 @@ public class Fraction
}
return str;
}
+
+ /**
+ * Parses a string that would be produced by {@link #toString()}
+ * and instantiates the corresponding object.
+ *
+ * @param s String representation.
+ * @return an instance.
+ * @throws IllegalArgumentException if the string does not
+ * conform to the specification.
+ */
+ public static Fraction parse(String s) {
+ final int len = s.length();
+ final int slashLoc = s.indexOf("/");
+ // if no slash, parse as single number
+ if (slashLoc == -1) {
+ return Fraction.of(Integer.parseInt(s));
+ } else {
+ final int num = Integer.parseInt(s.substring(0, slashLoc).trim());
+ final int denom = Integer.parseInt(s.substring(slashLoc + 1).trim());
+ return of(num, denom);
+ }
+ }
+
}
\ No newline at end of file