Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Recently I tried understanding the use of java.math.MathContext but failed to understand properly. Is it used for rounding in java.math.BigDecimal, if yes why does not it round the decimal digits but even mentissa part. From API docs, I came to know that it follows the standard specified in ANSI X3.274-1996 and ANSI X3.274-1996/AM 1-2000 specifications but I did not get them to read online. P...
I've been trying to figure this out, and the previously related questions on SO aren't helping me out either.. I need the following results 100.12 -> 100.00 100.44 -> 100.00 100.50 -> 101.00 100.75 -> 101.00 .round() or .setScale() ? How do i go about this? Thanks : )
Doing the following val num = BigDecimal(1.0) val den = BigDecimal(3.0) println((num/den)(MathContext.DECIMAL128)) I only get 0.3333333333333333333333333333333333 Which is less than the 128 I want
  /*
   * Portions Copyright 2003-2007 Sun Microsystems, Inc.  All Rights Reserved.
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   *
   * This code is free software; you can redistribute it and/or modify it
   * under the terms of the GNU General Public License version 2 only, as
   * published by the Free Software Foundation.  Sun designates this
   * particular file as subject to the "Classpath" exception as provided
   * by Sun in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  * version 2 for more details (a copy is included in the LICENSE file that
  * accompanied this code).
  *
  * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  * CA 95054 USA or visit www.sun.com if you need additional information or
  * have any questions.
  */
 
 /*
  * Portions Copyright IBM Corporation, 1997, 2001. All Rights Reserved.
  */
 
 package java.math;
 import java.io.*;

Immutable objects which encapsulate the context settings which describe certain rules for numerical operators, such as those implemented by the BigDecimal class.

The base-independent settings are:

  1. precision: the number of digits to be used for an operation; results are rounded to this precision
  2. roundingMode: a RoundingMode object which specifies the algorithm to be used for rounding.

Author(s):
Mike Cowlishaw
Joseph D. Darcy
Since:
1.5
See also:
BigDecimal
RoundingMode
 
 
 public final class MathContext implements Serializable {
 
     /* ----- Constants ----- */
 
     // defaults for constructors
     private static final int DEFAULT_DIGITS = 9;
     private static final RoundingMode DEFAULT_ROUNDINGMODE = .;
     // Smallest values for digits (Maximum is Integer.MAX_VALUE)
     private static final int MIN_DIGITS = 0;
 
     // Serialization version
     private static final long serialVersionUID = 5579720004786848255L;
 
     /* ----- Public Properties ----- */
    
A MathContext object whose settings have the values required for unlimited precision arithmetic. The values of the settings are: precision=0 roundingMode=HALF_UP
 
     public static final MathContext UNLIMITED =
         new MathContext(0, .);

    
A MathContext object with a precision setting matching the IEEE 754R Decimal32 format, 7 digits, and a rounding mode of HALF_EVEN, the IEEE 754R default.
 
     public static final MathContext DECIMAL32 =
         new MathContext(7, .);

    
A MathContext object with a precision setting matching the IEEE 754R Decimal64 format, 16 digits, and a rounding mode of HALF_EVEN, the IEEE 754R default.
 
     public static final MathContext DECIMAL64 =
         new MathContext(16, .);

    
A MathContext object with a precision setting matching the IEEE 754R Decimal128 format, 34 digits, and a rounding mode of HALF_EVEN, the IEEE 754R default.
    public static final MathContext DECIMAL128 =
        new MathContext(34, .);
    /* ----- Shared Properties ----- */
    
The number of digits to be used for an operation. A value of 0 indicates that unlimited precision (as many digits as are required) will be used. Note that leading zeros (in the coefficient of a number) are never significant.

precision will always be non-negative.

Serial:
    final int precision;

    
The rounding algorithm to be used for an operation.

See also:
RoundingMode
Serial:
    final RoundingMode roundingMode;

    
Lookaside for the rounding points (the numbers which determine whether the coefficient of a number will require rounding). These will be present if precision > 0 and precision <= MAX_LOOKASIDE. In this case they will share the BigInteger int[] array. Note that the transients cannot be final because they are reconstructed on deserialization.
    transient BigInteger roundingMax = null;
    transient BigInteger roundingMin = null;
    private static final int MAX_LOOKASIDE = 1000;
    /* ----- Constructors ----- */

    
Constructs a new MathContext with the specified precision and the HALF_UP rounding mode.

Parameters:
setPrecision The non-negative int precision setting.
Throws:
java.lang.IllegalArgumentException if the setPrecision parameter is less than zero.
    public MathContext(int setPrecision) {
        this(setPrecision);
        return;
    }

    
Constructs a new MathContext with a specified precision and rounding mode.

Parameters:
setPrecision The non-negative int precision setting.
setRoundingMode The rounding mode to use.
Throws:
java.lang.IllegalArgumentException if the setPrecision parameter is less than zero.
java.lang.NullPointerException if the rounding mode argument is null
    public MathContext(int setPrecision,
                       RoundingMode setRoundingMode) {
        if (setPrecision < )
            throw new IllegalArgumentException("Digits < 0");
        if (setRoundingMode == null)
            throw new NullPointerException("null RoundingMode");
         = setPrecision;
        if ( > 0 &&  <= ) {
             = ..pow();
             = .negate();
        }
         = setRoundingMode;
        return;
    }

    
Constructs a new MathContext from a string. The string must be in the same format as that produced by the toString() method.

An IllegalArgumentException is thrown if the precision section of the string is out of range (< 0) or the string is not in the format created by the toString() method.

Parameters:
val The string to be parsed
Throws:
java.lang.IllegalArgumentException if the precision section is out of range or of incorrect format
java.lang.NullPointerException if the argument is 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(offval.length());
             = RoundingMode.valueOf(str);
        } catch (RuntimeException re) {
            throw new IllegalArgumentException("bad string format");
        }
        if (setPrecision < )
            throw new IllegalArgumentException("Digits < 0");
        // the other parameters cannot be invalid if we got here
         = setPrecision;
        if ( > 0 &&  <= ) {
             = ..pow();
             = .negate();
        }
    }

    
Returns the precision setting. This value is always non-negative.

Returns:
an int which is the value of the precision setting
    public int getPrecision() {
        return ;
    }

    
Returns the roundingMode setting. This will be one of RoundingMode.CEILING, RoundingMode.DOWN, RoundingMode.FLOOR, RoundingMode.HALF_DOWN, RoundingMode.HALF_EVEN, RoundingMode.HALF_UP, RoundingMode.UNNECESSARY, or RoundingMode.UP.

Returns:
a RoundingMode object which is the value of the roundingMode setting
    public RoundingMode getRoundingMode() {
        return ;
    }

    
Compares this MathContext with the specified Object for equality.

Parameters:
x Object to which this MathContext is to be compared.
Returns:
true if and only if the specified Object is a MathContext object which has exactly the same settings as this object
    public boolean equals(Object x){
        MathContext mc;
        if (!(x instanceof MathContext))
            return false;
        mc = (MathContextx;
        return mc.precision == this.
            && mc.roundingMode == this.// no need for .equals()
    }

    
Returns the hash code for this MathContext.

Returns:
hash code for this MathContext
    public int hashCode() {
        return this. + .hashCode() * 59;
    }

    
Returns the string representation of this MathContext. The String returned represents the settings of the MathContext object as two space-delimited words (separated by a single space character, '\u0020', and with no leading or trailing white space), as follows:
  1. The string "precision=", immediately followed by the value of the precision setting as a numeric string as if generated by the Integer.toString method.
  2. The string "roundingMode=", immediately followed by the value of the roundingMode setting as a word. This word will be the same as the name of the corresponding public constant in the RoundingMode enum.

For example:

 precision=9 roundingMode=HALF_UP
 
Additional words may be appended to the result of toString in the future if more properties are added to this class.

Returns:
a String representing the context settings
    public java.lang.String toString() {
        return "precision=" +            + " " +
               "roundingMode=" +        .toString();
    }
    // Private methods

    
Reconstitute the MathContext instance from a stream (that is, deserialize it).

Parameters:
s the stream being read.
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOExceptionClassNotFoundException {
        s.defaultReadObject();     // read in all fields
        // validate possibly bad fields
        if ( < ) {
            String message = "MathContext: invalid digits in stream";
            throw new java.io.StreamCorruptedException(message);
        }
        if ( == null) {
            String message = "MathContext: null roundingMode in stream";
            throw new java.io.StreamCorruptedException(message);
        }
        // Set the lookaside, if applicable
        if ( <= ) {
             = ..pow();
             = .negate();
        }
    }
New to GrepCode? Check out our FAQ X