/** * Constructs a new {@code MathContext} from a string. * * <p>The string must be in the same format as that produced by the {@link #toString} method. * * <p>An {@code IllegalArgumentException} is thrown if the precision section of the string is out * of range ({@code < 0}) or the string is not in the format created by the {@link #toString} * method. * * @param val The string to be parsed * @throws IllegalArgumentException if the precision section is out of range or of incorrect * format * @throws NullPointerException if the argument is {@code null} */ public MathContext(String val) { boolean bad = false; int setPrecision; if (val == null) throw new NullPointerException("null String"); try { // any error here is a string format problem if (!val.startsWith("precision=")) throw new RuntimeException(); int fence = val.indexOf(' '); // could be -1 int off = 10; // where value starts setPrecision = Integer.parseInt(val.substring(10, fence)); if (!val.startsWith("roundingMode=", fence + 1)) throw new RuntimeException(); off = fence + 1 + 13; String str = val.substring(off, val.length()); roundingMode = RoundingMode.valueOf(str); } catch (RuntimeException re) { throw new IllegalArgumentException("bad string format"); } if (setPrecision < MIN_DIGITS) throw new IllegalArgumentException("Digits < 0"); // the other parameters cannot be invalid if we got here precision = setPrecision; }
/** * Returns the string representation of this {@code MathContext}. The {@code String} returned * represents the settings of the {@code MathContext} object as two space-delimited words * (separated by a single space character, <tt>'\u0020'</tt>, and with no leading or trailing * white space), as follows: * * <ol> * <li>The string {@code "precision="}, immediately followed by the value of the precision * setting as a numeric string as if generated by the {@link Integer#toString(int) * Integer.toString} method. * <li>The string {@code "roundingMode="}, immediately followed by the value of the {@code * roundingMode} setting as a word. This word will be the same as the name of the * corresponding public constant in the {@link RoundingMode} enum. * </ol> * * <p>For example: * * <pre> * precision=9 roundingMode=HALF_UP * </pre> * * Additional words may be appended to the result of {@code toString} in the future if more * properties are added to this class. * * @return a {@code String} representing the context settings */ public java.lang.String toString() { return "precision=" + precision + " " + "roundingMode=" + roundingMode.toString(); }
/** * Returns the hash code for this {@code MathContext}. * * @return hash code for this {@code MathContext} */ public int hashCode() { return this.precision + roundingMode.hashCode() * 59; }