我是靠谱客的博主 爱笑冷风,最近开发中收集的这篇文章主要介绍BigDecimal的RoundingMode舍入模式与MathContext,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

精确计算时,经常会涉及到“保留位数”或“数值舍入”的情况。

“保留位数”说白了就是“数值舍入”。舍入的关键就是规定好舍入时对保留位数如何进位。RoundingMode就提供了舍入的8种进位规则。

说再多也比不上源码!直接上JDK8的源码。而且源码里有注释有解说还有示例,清晰明了。

/*
 * %W% %E%
 *
 * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

/*
 * @(#)RoundingMode.java  1.x 01/xx/xx
 *
 * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
 * Portions Copyright IBM Corporation, 2001. All Rights Reserved.
 *
 * This software is the proprietary information of Oracle.
 * Use is subject to license terms.
 *
 */
package java.math;

/**
 * Specifies a <i>rounding behavior</i> for numerical operations
 * capable of discarding precision. Each rounding mode indicates how
 * the least significant returned digit of a rounded result is to be
 * calculated.  If fewer digits are returned than the digits needed to
 * represent the exact numerical result, the discarded digits will be
 * referred to as the <i>discarded fraction</i> regardless the digits'
 * contribution to the value of the number.  In other words,
 * considered as a numerical value, the discarded fraction could have
 * an absolute value greater than one.
 *
 * <p>Each rounding mode description includes a table listing how
 * different two-digit decimal values would round to a one digit
 * decimal value under the rounding mode in question.  The result
 * column in the tables could be gotten by creating a
 * <tt>BigDecimal</tt> number with the specified value, forming a
 * {@link MathContext} object with the proper settings
 * (<tt>precision</tt> set to <tt>1</tt>, and the
 * <tt>roundingMode</tt> set to the rounding mode in question), and
 * calling {@link BigDecimal#round round} on this number with the
 * proper <tt>MathContext</tt>.  A summary table showing the results
 * of these rounding operations for all rounding modes appears below.
 *
 *<p>
 *<table border>
 * <caption top><h3>Summary of Rounding Operations Under Different Rounding Modes</h3></caption>
 * <tr><th></th><th colspan=8>Result of rounding input to one digit with the given 
 *                           rounding mode</th>
 * <tr valign=top>
 * <th>Input Number</th>	 <th><tt>UP</tt></th> 
 *                                           <th><tt>DOWN</tt></th> 
 *                                                        <th><tt>CEILING</tt></th>
 *                                                                       <th><tt>FLOOR</tt></th>
 *                                                                                    <th><tt>HALF_UP</tt></th>
 *                                                                                                   <th><tt>HALF_DOWN</tt></th>
 *                                                                                                                    <th><tt>HALF_EVEN</tt></th>
 *                                                                                                                                     <th><tt>UNNECESSARY</tt></th>
 *    
 * <tr align=right><td>5.5</td>	 <td>6</td>  <td>5</td>    <td>6</td>    <td>5</td>  <td>6</td>      <td>5</td>       <td>6</td>       <td>throw <tt>ArithmeticException</tt></td>
 * <tr align=right><td>2.5</td>	 <td>3</td>  <td>2</td>    <td>3</td>    <td>2</td>  <td>3</td>      <td>2</td>       <td>2</td>       <td>throw <tt>ArithmeticException</tt></td>
 * <tr align=right><td>1.6</td>	 <td>2</td>  <td>1</td>    <td>2</td> 	 <td>1</td>  <td>2</td>      <td>2</td>       <td>2</td>       <td>throw <tt>ArithmeticException</tt></td>
 * <tr align=right><td>1.1</td>	 <td>2</td>  <td>1</td>    <td>2</td> 	 <td>1</td>  <td>1</td>      <td>1</td>       <td>1</td>       <td>throw <tt>ArithmeticException</tt></td>
 * <tr align=right><td>1.0</td>	 <td>1</td>  <td>1</td>    <td>1</td> 	 <td>1</td>  <td>1</td>      <td>1</td>       <td>1</td>       <td>1</td>                                
 * <tr align=right><td>-1.0</td> <td>-1</td> <td>-1</td>   <td>-1</td>	 <td>-1</td> <td>-1</td>     <td>-1</td>      <td>-1</td>      <td>-1</td>                               
 * <tr align=right><td>-1.1</td> <td>-2</td> <td>-1</td>   <td>-1</td>	 <td>-2</td> <td>-1</td>     <td>-1</td>      <td>-1</td>      <td>throw <tt>ArithmeticException</tt></td>
 * <tr align=right><td>-1.6</td> <td>-2</td> <td>-1</td>   <td>-1</td>	 <td>-2</td> <td>-2</td>     <td>-2</td>      <td>-2</td>      <td>throw <tt>ArithmeticException</tt></td>
 * <tr align=right><td>-2.5</td> <td>-3</td> <td>-2</td>   <td>-2</td>	 <td>-3</td> <td>-3</td>     <td>-2</td>      <td>-2</td>      <td>throw <tt>ArithmeticException</tt></td>
 * <tr align=right><td>-5.5</td> <td>-6</td> <td>-5</td>   <td>-5</td>	 <td>-6</td> <td>-6</td>     <td>-5</td>      <td>-6</td>      <td>throw <tt>ArithmeticException</tt></td>
 *</table>
 *
 * 
 * <p>This <tt>enum</tt> is intended to replace the integer-based
 * enumeration of rounding mode constants in {@link BigDecimal}
 * ({@link BigDecimal#ROUND_UP}, {@link BigDecimal#ROUND_DOWN},
 * etc. ).
 *
 * @see     BigDecimal
 * @see     MathContext
 * @version 1.x 01/xx/xx
 * @author  Josh Bloch
 * @author  Mike Cowlishaw
 * @author  Joseph D. Darcy
 * @since 1.5
 */
public enum RoundingMode {

	/**
	 * Rounding mode to round away from zero.  Always increments the
	 * digit prior to a non-zero discarded fraction.  Note that this
	 * rounding mode never decreases the magnitude of the calculated
	 * value.
	 *
	 *<p>Example:
	 *<table border>
	 *<tr valign=top><th>Input Number</th>
	 *    <th>Input rounded to one digit<br> with <tt>UP</tt> rounding
	 *<tr align=right><td>5.5</td>	<td>6</td>
	 *<tr align=right><td>2.5</td>	<td>3</td>
	 *<tr align=right><td>1.6</td>	<td>2</td>
	 *<tr align=right><td>1.1</td>	<td>2</td>
	 *<tr align=right><td>1.0</td>	<td>1</td>
	 *<tr align=right><td>-1.0</td>	<td>-1</td>
	 *<tr align=right><td>-1.1</td>	<td>-2</td>
	 *<tr align=right><td>-1.6</td>	<td>-2</td>
	 *<tr align=right><td>-2.5</td>	<td>-3</td>
	 *<tr align=right><td>-5.5</td>	<td>-6</td>
	 *</table>
	 */
    UP(BigDecimal.ROUND_UP),
	    
	/**
	 * Rounding mode to round towards zero.  Never increments the digit
	 * prior to a discarded fraction (i.e., truncates).  Note that this
	 * rounding mode never increases the magnitude of the calculated value.
	 *
	 *<p>Example:
	 *<table border>
	 *<tr valign=top><th>Input Number</th>
	 *    <th>Input rounded to one digit<br> with <tt>DOWN</tt> rounding
	 *<tr align=right><td>5.5</td>	<td>5</td>
	 *<tr align=right><td>2.5</td>	<td>2</td>
	 *<tr align=right><td>1.6</td>	<td>1</td>
	 *<tr align=right><td>1.1</td>	<td>1</td>
	 *<tr align=right><td>1.0</td>	<td>1</td>
	 *<tr align=right><td>-1.0</td>	<td>-1</td>
	 *<tr align=right><td>-1.1</td>	<td>-1</td>
	 *<tr align=right><td>-1.6</td>	<td>-1</td>
	 *<tr align=right><td>-2.5</td>	<td>-2</td>
	 *<tr align=right><td>-5.5</td>	<td>-5</td>
	 *</table>
	 */
    DOWN(BigDecimal.ROUND_DOWN),
	    
	/**
	 * Rounding mode to round towards positive infinity.  If the
	 * result is positive, behaves as for <tt>RoundingMode.UP</tt>;
	 * if negative, behaves as for <tt>RoundingMode.DOWN</tt>.  Note
	 * that this rounding mode never decreases the calculated value.
	 *
	 *<p>Example:
	 *<table border>
	 *<tr valign=top><th>Input Number</th>
	 *    <th>Input rounded to one digit<br> with <tt>CEILING</tt> rounding
	 *<tr align=right><td>5.5</td>	<td>6</td>
	 *<tr align=right><td>2.5</td>	<td>3</td>
	 *<tr align=right><td>1.6</td>	<td>2</td>
	 *<tr align=right><td>1.1</td>	<td>2</td>
	 *<tr align=right><td>1.0</td>	<td>1</td>
	 *<tr align=right><td>-1.0</td>	<td>-1</td>
	 *<tr align=right><td>-1.1</td>	<td>-1</td>
	 *<tr align=right><td>-1.6</td>	<td>-1</td>
	 *<tr align=right><td>-2.5</td>	<td>-2</td>
	 *<tr align=right><td>-5.5</td>	<td>-5</td>
	 *</table>
	 */
    CEILING(BigDecimal.ROUND_CEILING),

	/**
	 * Rounding mode to round towards negative infinity.  If the
	 * result is positive, behave as for <tt>RoundingMode.DOWN</tt>;
	 * if negative, behave as for <tt>RoundingMode.UP</tt>.  Note that
	 * this rounding mode never increases the calculated value.
	 *
	 *<p>Example:
	 *<table border>
	 *<tr valign=top><th>Input Number</th>
	 *    <th>Input rounded to one digit<br> with <tt>FLOOR</tt> rounding
	 *<tr align=right><td>5.5</td>	<td>5</td>
	 *<tr align=right><td>2.5</td>	<td>2</td>
	 *<tr align=right><td>1.6</td>	<td>1</td>
	 *<tr align=right><td>1.1</td>	<td>1</td>
	 *<tr align=right><td>1.0</td>	<td>1</td>
	 *<tr align=right><td>-1.0</td>	<td>-1</td>
	 *<tr align=right><td>-1.1</td>	<td>-2</td>
	 *<tr align=right><td>-1.6</td>	<td>-2</td>
	 *<tr align=right><td>-2.5</td>	<td>-3</td>
	 *<tr align=right><td>-5.5</td>	<td>-6</td>
	 *</table>
	 */
    FLOOR(BigDecimal.ROUND_FLOOR),

	/**
	 * Rounding mode to round towards "nearest neighbor"
	 * unless both neighbors are equidistant, in which case round up.
	 * Behaves as for <tt>RoundingMode.UP</tt> if the discarded
	 * fraction is >= 0.5; otherwise, behaves as for
	 * <tt>RoundingMode.DOWN</tt>.  Note that this is the rounding
	 * mode commonly taught at school.
	 *
	 *<p>Example:
	 *<table border>
	 *<tr valign=top><th>Input Number</th>
	 *    <th>Input rounded to one digit<br> with <tt>HALF_UP</tt> rounding
	 *<tr align=right><td>5.5</td>	<td>6</td>
	 *<tr align=right><td>2.5</td>	<td>3</td>
	 *<tr align=right><td>1.6</td>	<td>2</td>
	 *<tr align=right><td>1.1</td>	<td>1</td>
	 *<tr align=right><td>1.0</td>	<td>1</td>
	 *<tr align=right><td>-1.0</td>	<td>-1</td>
	 *<tr align=right><td>-1.1</td>	<td>-1</td>
	 *<tr align=right><td>-1.6</td>	<td>-2</td>
	 *<tr align=right><td>-2.5</td>	<td>-3</td>
	 *<tr align=right><td>-5.5</td>	<td>-6</td>
	 *</table>
	 */
    HALF_UP(BigDecimal.ROUND_HALF_UP),

	/**
	 * Rounding mode to round towards "nearest neighbor"
	 * unless both neighbors are equidistant, in which case round
	 * down.  Behaves as for <tt>RoundingMode.UP</tt> if the discarded
	 * fraction is > 0.5; otherwise, behaves as for
	 * <tt>RoundingMode.DOWN</tt>.
	 *
	 *<p>Example:
	 *<table border>
	 *<tr valign=top><th>Input Number</th>
	 *    <th>Input rounded to one digit<br> with <tt>HALF_DOWN</tt> rounding
	 *<tr align=right><td>5.5</td>	<td>5</td>
	 *<tr align=right><td>2.5</td>	<td>2</td>
	 *<tr align=right><td>1.6</td>	<td>2</td>
	 *<tr align=right><td>1.1</td>	<td>1</td>
	 *<tr align=right><td>1.0</td>	<td>1</td>
	 *<tr align=right><td>-1.0</td>	<td>-1</td>
	 *<tr align=right><td>-1.1</td>	<td>-1</td>
	 *<tr align=right><td>-1.6</td>	<td>-2</td>
	 *<tr align=right><td>-2.5</td>	<td>-2</td>
	 *<tr align=right><td>-5.5</td>	<td>-5</td>
	 *</table>
	 */
    HALF_DOWN(BigDecimal.ROUND_HALF_DOWN),

	/**
	 * Rounding mode to round towards the "nearest neighbor"
	 * unless both neighbors are equidistant, in which case, round
	 * towards the even neighbor.  Behaves as for
	 * <tt>RoundingMode.HALF_UP</tt> if the digit to the left of the
	 * discarded fraction is odd; behaves as for
	 * <tt>RoundingMode.HALF_DOWN</tt> if it's even.  Note that this
	 * is the rounding mode that statistically minimizes cumulative
	 * error when applied repeatedly over a sequence of calculations.
	 * It is sometimes known as "Banker's rounding," and is
	 * chiefly used in the USA.  This rounding mode is analogous to
	 * the rounding policy used for <tt>float</tt> and <tt>double</tt>
	 * arithmetic in Java.
	 *
	 *<p>Example:
	 *<table border>
	 *<tr valign=top><th>Input Number</th>
	 *    <th>Input rounded to one digit<br> with <tt>HALF_EVEN</tt> rounding
	 *<tr align=right><td>5.5</td>	<td>6</td>
	 *<tr align=right><td>2.5</td>	<td>2</td>
	 *<tr align=right><td>1.6</td>	<td>2</td>
	 *<tr align=right><td>1.1</td>	<td>1</td>
	 *<tr align=right><td>1.0</td>	<td>1</td>
	 *<tr align=right><td>-1.0</td>	<td>-1</td>
	 *<tr align=right><td>-1.1</td>	<td>-1</td>
	 *<tr align=right><td>-1.6</td>	<td>-2</td>
	 *<tr align=right><td>-2.5</td>	<td>-2</td>
	 *<tr align=right><td>-5.5</td>	<td>-6</td>
	 *</table>
	 */
    HALF_EVEN(BigDecimal.ROUND_HALF_EVEN),

	/**
	 * Rounding mode to assert that the requested operation has an exact
	 * result, hence no rounding is necessary.  If this rounding mode is
	 * specified on an operation that yields an inexact result, an
	 * <tt>ArithmeticException</tt> is thrown.
	 *<p>Example:
	 *<table border>
	 *<tr valign=top><th>Input Number</th>
	 *    <th>Input rounded to one digit<br> with <tt>UNNECESSARY</tt> rounding
	 *<tr align=right><td>5.5</td>	<td>throw <tt>ArithmeticException</tt></td>
	 *<tr align=right><td>2.5</td>	<td>throw <tt>ArithmeticException</tt></td>
	 *<tr align=right><td>1.6</td>	<td>throw <tt>ArithmeticException</tt></td>
	 *<tr align=right><td>1.1</td>	<td>throw <tt>ArithmeticException</tt></td>
	 *<tr align=right><td>1.0</td>	<td>1</td>
	 *<tr align=right><td>-1.0</td>	<td>-1</td>
	 *<tr align=right><td>-1.1</td>	<td>throw <tt>ArithmeticException</tt></td>
	 *<tr align=right><td>-1.6</td>	<td>throw <tt>ArithmeticException</tt></td>
	 *<tr align=right><td>-2.5</td>	<td>throw <tt>ArithmeticException</tt></td>
	 *<tr align=right><td>-5.5</td>	<td>throw <tt>ArithmeticException</tt></td>	
	 *</table>
	 */
    UNNECESSARY(BigDecimal.ROUND_UNNECESSARY);

    // Corresponding BigDecimal rounding constant
    final int oldMode;

    /**
     * Constructor
     *
     * @param oldMode The <tt>BigDecimal</tt> constant corresponding to 
     *        this mode
     */
    private RoundingMode(int oldMode) {
        this.oldMode = oldMode;
    }

    /**
     * Returns the <tt>RoundingMode</tt> object corresponding to a
     * legacy integer rounding mode constant in {@link BigDecimal}.
     *
     * @param  rm legacy integer rounding mode to convert
     * @return <tt>RoundingMode</tt> corresponding to the given integer.
     * @throws IllegalArgumentException integer is out of range
     */
    public static RoundingMode valueOf(int rm) {
	switch(rm) {

	case BigDecimal.ROUND_UP:
	    return UP;

	case BigDecimal.ROUND_DOWN:
	    return DOWN;

	case BigDecimal.ROUND_CEILING:
	    return CEILING;
	    
	case BigDecimal.ROUND_FLOOR:
	    return FLOOR;

	case BigDecimal.ROUND_HALF_UP:
	    return HALF_UP;
	    
	case BigDecimal.ROUND_HALF_DOWN:
	    return HALF_DOWN;
	    
	case BigDecimal.ROUND_HALF_EVEN:
	    return HALF_EVEN;
	    
	case BigDecimal.ROUND_UNNECESSARY:
	    return UNNECESSARY;
	    
	default:
	    throw new IllegalArgumentException("argument out of range");		
	}
    }
}

看完了源码,我理解后总结出来的记忆秘籍是:(关键字“都要”)。

下面的例子,都是舍去小数位,只保留到个位数。舍去小数位时对保留的个位数如何进位,RoundingMode提供的8种规则如下:

1.UP:不管是正数还是负数,按其在Y轴上的位置,如有被舍位数都要取其趋于U两端±的值;

  如1.1~1.9的趋于+∞的值是2,-1.9~-1.1的趋于-∞的值是-2;

2.DOWN:不管是正数还是负数,按其在Y轴上的位置,如有被舍位数都要取其趋于0的值;

  如1.1~1.9的趋于0的值是1,-1.9~-1.1趋于0的值是-1;

3.CEILING:不管是正数还是负数,按其在Y轴上的位置,如有被舍位数都要取其CEILING天花板值;

  如1.1~1.9的CEILING天花板值是2,-1.9~-1.1的CEILING天花板值是-1;

4.FLOOR:不管是正数还是负数,按其在Y轴上的位置,如有被舍位数都要取其FLOOR地板值;

  如1.1~1.9的FLOOR地板值是1,-1.9~-1.1的FLOOR地板值是-2;

理解识记以上4个就很好办了,另外4个是衍生出来的:

5.HALF_UP:不管是正数还是负数,按其在Y轴上的位置,被舍位数如果up than half达半(即0.5~0.9)都要取其趋于U两端±的值(潜台词:反之则取其趋于0的值),即五入四舍;

  如1.5和-1.5达半要取趋于±∞的值2和-2,1.4和-1.4未达半只能取趋于0的值1和-1;

6.HALF_DOWN:不管是正数还是负数,按其在Y轴上的位置,被舍位数如果down than half未过半(即0.1~0.5)都要取其趋于0的值(潜台词:反之则取其趋于U两端±的值),即五舍六入;

  如1.5和-1.5未过半要取趋于0的值1和-1,1.6和-1.6过半只能取趋于±∞的值2和-2;

7.HALF_EVEN:不管是正数还是负数,按其在Y轴上的位置,如有被舍位数都要取其趋于EVEN公平的值(潜台词:向谁靠拢就取谁,但0.5正居中间要根据保留位数的奇偶来奇up偶down);

  如1.4和-1.4向1和-1靠拢;1.6和-1.6向2和-2靠拢;

  如1.5和-1.5保留的个位数是奇数1则up取趋于±∞的值2和-2,2.5和-2.5保留的个位数是偶数2则down取趋于0的值2和-2;

8.UNNECESSARY:不需要做数值的舍入;经常在除法时抛错,除不尽时会抛出ArithmeticException。

/*
 * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

/*
 * 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 {@link BigDecimal} class.
 *
 * <p>The base-independent settings are:
 * <ol>
 * <li>{@code precision}:
 * the number of digits to be used for an operation; results are
 * rounded to this precision
 *
 * <li>{@code roundingMode}:
 * a {@link RoundingMode} object which specifies the algorithm to be
 * used for rounding.
 * </ol>
 *
 * @see     BigDecimal
 * @see     RoundingMode
 * @author  Mike Cowlishaw
 * @author  Joseph D. Darcy
 * @since 1.5
 */

public final class MathContext implements Serializable {

    /* ----- Constants ----- */

    // defaults for constructors
    private static final int DEFAULT_DIGITS = 9;
    private static final RoundingMode DEFAULT_ROUNDINGMODE = RoundingMode.HALF_UP;
    // 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 {@code MathContext} object whose settings have the values
     *  required for unlimited precision arithmetic.
     *  The values of the settings are:
     *  <code>
     *  precision=0 roundingMode=HALF_UP
     *  </code>
     */
    public static final MathContext UNLIMITED =
        new MathContext(0, RoundingMode.HALF_UP);

    /**
     *  A {@code MathContext} object with a precision setting
     *  matching the IEEE 754R Decimal32 format, 7 digits, and a
     *  rounding mode of {@link RoundingMode#HALF_EVEN HALF_EVEN}, the
     *  IEEE 754R default.
     */
    public static final MathContext DECIMAL32 =
        new MathContext(7, RoundingMode.HALF_EVEN);

    /**
     *  A {@code MathContext} object with a precision setting
     *  matching the IEEE 754R Decimal64 format, 16 digits, and a
     *  rounding mode of {@link RoundingMode#HALF_EVEN HALF_EVEN}, the
     *  IEEE 754R default.
     */
    public static final MathContext DECIMAL64 =
        new MathContext(16, RoundingMode.HALF_EVEN);

    /**
     *  A {@code MathContext} object with a precision setting
     *  matching the IEEE 754R Decimal128 format, 34 digits, and a
     *  rounding mode of {@link RoundingMode#HALF_EVEN HALF_EVEN}, the
     *  IEEE 754R default.
     */
    public static final MathContext DECIMAL128 =
        new MathContext(34, RoundingMode.HALF_EVEN);

    /* ----- 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.
     *
     * <p>{@code precision} will always be non-negative.
     *
     * @serial
     */
    final int precision;

    /**
     * The rounding algorithm to be used for an operation.
     *
     * @see RoundingMode
     * @serial
     */
    final RoundingMode roundingMode;

    /* ----- Constructors ----- */

    /**
     * Constructs a new {@code MathContext} with the specified
     * precision and the {@link RoundingMode#HALF_UP HALF_UP} rounding
     * mode.
     *
     * @param setPrecision The non-negative {@code int} precision setting.
     * @throws IllegalArgumentException if the {@code setPrecision} parameter is less
     *         than zero.
     */
    public MathContext(int setPrecision) {
        this(setPrecision, DEFAULT_ROUNDINGMODE);
        return;
    }

    /**
     * Constructs a new {@code MathContext} with a specified
     * precision and rounding mode.
     *
     * @param setPrecision The non-negative {@code int} precision setting.
     * @param setRoundingMode The rounding mode to use.
     * @throws IllegalArgumentException if the {@code setPrecision} parameter is less
     *         than zero.
     * @throws NullPointerException if the rounding mode argument is {@code null}
     */
    public MathContext(int setPrecision,
                       RoundingMode setRoundingMode) {
        if (setPrecision < MIN_DIGITS)
            throw new IllegalArgumentException("Digits < 0");
        if (setRoundingMode == null)
            throw new NullPointerException("null RoundingMode");

        precision = setPrecision;
        roundingMode = setRoundingMode;
        return;
    }

    /**
     * Constructs a new {@code MathContext} from a string.
     *
     * 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 {@code precision} setting.
     * This value is always non-negative.
     *
     * @return an {@code int} which is the value of the {@code precision}
     *         setting
     */
    public int getPrecision() {
        return precision;
    }

    /**
     * Returns the roundingMode setting.
     * This will be one of
     * {@link  RoundingMode#CEILING},
     * {@link  RoundingMode#DOWN},
     * {@link  RoundingMode#FLOOR},
     * {@link  RoundingMode#HALF_DOWN},
     * {@link  RoundingMode#HALF_EVEN},
     * {@link  RoundingMode#HALF_UP},
     * {@link  RoundingMode#UNNECESSARY}, or
     * {@link  RoundingMode#UP}.
     *
     * @return a {@code RoundingMode} object which is the value of the
     *         {@code roundingMode} setting
     */

    public RoundingMode getRoundingMode() {
        return roundingMode;
    }

    /**
     * Compares this {@code MathContext} with the specified
     * {@code Object} for equality.
     *
     * @param  x {@code Object} to which this {@code MathContext} is to
     *         be compared.
     * @return {@code true} if and only if the specified {@code Object} is
     *         a {@code 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 = (MathContext) x;
        return mc.precision == this.precision
            && mc.roundingMode == this.roundingMode; // no need for .equals()
    }

    /**
     * Returns the hash code for this {@code MathContext}.
     *
     * @return hash code for this {@code MathContext}
     */
    public int hashCode() {
        return this.precision + roundingMode.hashCode() * 59;
    }

    /**
     * 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();
    }

    // Private methods

    /**
     * Reconstitute the {@code MathContext} instance from a stream (that is,
     * deserialize it).
     *
     * @param s the stream being read.
     */
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        s.defaultReadObject();     // read in all fields
        // validate possibly bad fields
        if (precision < MIN_DIGITS) {
            String message = "MathContext: invalid digits in stream";
            throw new java.io.StreamCorruptedException(message);
        }
        if (roundingMode == null) {
            String message = "MathContext: null roundingMode in stream";
            throw new java.io.StreamCorruptedException(message);
        }
    }

}

最后

以上就是爱笑冷风为你收集整理的BigDecimal的RoundingMode舍入模式与MathContext的全部内容,希望文章能够帮你解决BigDecimal的RoundingMode舍入模式与MathContext所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(37)

评论列表共有 0 条评论

立即
投稿
返回
顶部