Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/math/MathContext.java
38829 views
/*1* Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* Portions Copyright IBM Corporation, 1997, 2001. All Rights Reserved.27*/2829package java.math;30import java.io.*;3132/**33* Immutable objects which encapsulate the context settings which34* describe certain rules for numerical operators, such as those35* implemented by the {@link BigDecimal} class.36*37* <p>The base-independent settings are:38* <ol>39* <li>{@code precision}:40* the number of digits to be used for an operation; results are41* rounded to this precision42*43* <li>{@code roundingMode}:44* a {@link RoundingMode} object which specifies the algorithm to be45* used for rounding.46* </ol>47*48* @see BigDecimal49* @see RoundingMode50* @author Mike Cowlishaw51* @author Joseph D. Darcy52* @since 1.553*/5455public final class MathContext implements Serializable {5657/* ----- Constants ----- */5859// defaults for constructors60private static final int DEFAULT_DIGITS = 9;61private static final RoundingMode DEFAULT_ROUNDINGMODE = RoundingMode.HALF_UP;62// Smallest values for digits (Maximum is Integer.MAX_VALUE)63private static final int MIN_DIGITS = 0;6465// Serialization version66private static final long serialVersionUID = 5579720004786848255L;6768/* ----- Public Properties ----- */69/**70* A {@code MathContext} object whose settings have the values71* required for unlimited precision arithmetic.72* The values of the settings are:73* <code>74* precision=0 roundingMode=HALF_UP75* </code>76*/77public static final MathContext UNLIMITED =78new MathContext(0, RoundingMode.HALF_UP);7980/**81* A {@code MathContext} object with a precision setting82* matching the IEEE 754R Decimal32 format, 7 digits, and a83* rounding mode of {@link RoundingMode#HALF_EVEN HALF_EVEN}, the84* IEEE 754R default.85*/86public static final MathContext DECIMAL32 =87new MathContext(7, RoundingMode.HALF_EVEN);8889/**90* A {@code MathContext} object with a precision setting91* matching the IEEE 754R Decimal64 format, 16 digits, and a92* rounding mode of {@link RoundingMode#HALF_EVEN HALF_EVEN}, the93* IEEE 754R default.94*/95public static final MathContext DECIMAL64 =96new MathContext(16, RoundingMode.HALF_EVEN);9798/**99* A {@code MathContext} object with a precision setting100* matching the IEEE 754R Decimal128 format, 34 digits, and a101* rounding mode of {@link RoundingMode#HALF_EVEN HALF_EVEN}, the102* IEEE 754R default.103*/104public static final MathContext DECIMAL128 =105new MathContext(34, RoundingMode.HALF_EVEN);106107/* ----- Shared Properties ----- */108/**109* The number of digits to be used for an operation. A value of 0110* indicates that unlimited precision (as many digits as are111* required) will be used. Note that leading zeros (in the112* coefficient of a number) are never significant.113*114* <p>{@code precision} will always be non-negative.115*116* @serial117*/118final int precision;119120/**121* The rounding algorithm to be used for an operation.122*123* @see RoundingMode124* @serial125*/126final RoundingMode roundingMode;127128/* ----- Constructors ----- */129130/**131* Constructs a new {@code MathContext} with the specified132* precision and the {@link RoundingMode#HALF_UP HALF_UP} rounding133* mode.134*135* @param setPrecision The non-negative {@code int} precision setting.136* @throws IllegalArgumentException if the {@code setPrecision} parameter is less137* than zero.138*/139public MathContext(int setPrecision) {140this(setPrecision, DEFAULT_ROUNDINGMODE);141return;142}143144/**145* Constructs a new {@code MathContext} with a specified146* precision and rounding mode.147*148* @param setPrecision The non-negative {@code int} precision setting.149* @param setRoundingMode The rounding mode to use.150* @throws IllegalArgumentException if the {@code setPrecision} parameter is less151* than zero.152* @throws NullPointerException if the rounding mode argument is {@code null}153*/154public MathContext(int setPrecision,155RoundingMode setRoundingMode) {156if (setPrecision < MIN_DIGITS)157throw new IllegalArgumentException("Digits < 0");158if (setRoundingMode == null)159throw new NullPointerException("null RoundingMode");160161precision = setPrecision;162roundingMode = setRoundingMode;163return;164}165166/**167* Constructs a new {@code MathContext} from a string.168*169* The string must be in the same format as that produced by the170* {@link #toString} method.171*172* <p>An {@code IllegalArgumentException} is thrown if the precision173* section of the string is out of range ({@code < 0}) or the string is174* not in the format created by the {@link #toString} method.175*176* @param val The string to be parsed177* @throws IllegalArgumentException if the precision section is out of range178* or of incorrect format179* @throws NullPointerException if the argument is {@code null}180*/181public MathContext(String val) {182boolean bad = false;183int setPrecision;184if (val == null)185throw new NullPointerException("null String");186try { // any error here is a string format problem187if (!val.startsWith("precision=")) throw new RuntimeException();188int fence = val.indexOf(' '); // could be -1189int off = 10; // where value starts190setPrecision = Integer.parseInt(val.substring(10, fence));191192if (!val.startsWith("roundingMode=", fence+1))193throw new RuntimeException();194off = fence + 1 + 13;195String str = val.substring(off, val.length());196roundingMode = RoundingMode.valueOf(str);197} catch (RuntimeException re) {198throw new IllegalArgumentException("bad string format");199}200201if (setPrecision < MIN_DIGITS)202throw new IllegalArgumentException("Digits < 0");203// the other parameters cannot be invalid if we got here204precision = setPrecision;205}206207/**208* Returns the {@code precision} setting.209* This value is always non-negative.210*211* @return an {@code int} which is the value of the {@code precision}212* setting213*/214public int getPrecision() {215return precision;216}217218/**219* Returns the roundingMode setting.220* This will be one of221* {@link RoundingMode#CEILING},222* {@link RoundingMode#DOWN},223* {@link RoundingMode#FLOOR},224* {@link RoundingMode#HALF_DOWN},225* {@link RoundingMode#HALF_EVEN},226* {@link RoundingMode#HALF_UP},227* {@link RoundingMode#UNNECESSARY}, or228* {@link RoundingMode#UP}.229*230* @return a {@code RoundingMode} object which is the value of the231* {@code roundingMode} setting232*/233234public RoundingMode getRoundingMode() {235return roundingMode;236}237238/**239* Compares this {@code MathContext} with the specified240* {@code Object} for equality.241*242* @param x {@code Object} to which this {@code MathContext} is to243* be compared.244* @return {@code true} if and only if the specified {@code Object} is245* a {@code MathContext} object which has exactly the same246* settings as this object247*/248public boolean equals(Object x){249MathContext mc;250if (!(x instanceof MathContext))251return false;252mc = (MathContext) x;253return mc.precision == this.precision254&& mc.roundingMode == this.roundingMode; // no need for .equals()255}256257/**258* Returns the hash code for this {@code MathContext}.259*260* @return hash code for this {@code MathContext}261*/262public int hashCode() {263return this.precision + roundingMode.hashCode() * 59;264}265266/**267* Returns the string representation of this {@code MathContext}.268* The {@code String} returned represents the settings of the269* {@code MathContext} object as two space-delimited words270* (separated by a single space character, <tt>'\u0020'</tt>,271* and with no leading or trailing white space), as follows:272* <ol>273* <li>274* The string {@code "precision="}, immediately followed275* by the value of the precision setting as a numeric string as if276* generated by the {@link Integer#toString(int) Integer.toString}277* method.278*279* <li>280* The string {@code "roundingMode="}, immediately281* followed by the value of the {@code roundingMode} setting as a282* word. This word will be the same as the name of the283* corresponding public constant in the {@link RoundingMode}284* enum.285* </ol>286* <p>287* For example:288* <pre>289* precision=9 roundingMode=HALF_UP290* </pre>291*292* Additional words may be appended to the result of293* {@code toString} in the future if more properties are added to294* this class.295*296* @return a {@code String} representing the context settings297*/298public java.lang.String toString() {299return "precision=" + precision + " " +300"roundingMode=" + roundingMode.toString();301}302303// Private methods304305/**306* Reconstitute the {@code MathContext} instance from a stream (that is,307* deserialize it).308*309* @param s the stream being read.310*/311private void readObject(java.io.ObjectInputStream s)312throws java.io.IOException, ClassNotFoundException {313s.defaultReadObject(); // read in all fields314// validate possibly bad fields315if (precision < MIN_DIGITS) {316String message = "MathContext: invalid digits in stream";317throw new java.io.StreamCorruptedException(message);318}319if (roundingMode == null) {320String message = "MathContext: null roundingMode in stream";321throw new java.io.StreamCorruptedException(message);322}323}324325}326327328