BigDecimal

class BigDecimal : Comparable<BigDecimal>

Immutable, arbitrary-precision signed decimal numbers. A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale. The value of the number represented by the BigDecimal is therefore unscaledValue 10^(-scale).

The BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion. The BigDecimal.toString method provides a canonical representation of a BigDecimal.

The BigDecimal class gives its user complete control over rounding behavior. If no rounding mode is specified and the exact result cannot be represented, an exception is thrown; otherwise, calculations can be carried out to a chosen _precision and rounding mode by supplying an appropriate MathContext object to the operation. In either case, eight rounding modes are provided for the control of rounding. Using the integer fields in this class (such as BigDecimal.ROUND_HALF_UP) to represent rounding mode is deprecated; the enumeration values of the RoundingModeenum, (such as RoundingMode.HALF_UP) should be used instead.

When a MathContext object is supplied with a _precision setting of 0 (for example, MathContext.UNLIMITED), arithmetic operations are exact, as are the arithmetic methods which take no MathContext object. (This is the only behavior that was supported in releases prior to 5.) As a corollary of computing the exact result, the rounding mode setting of a MathContext object with a _precision setting of 0 is not used and thus irrelevant. In the case of div, the exact quotient could have an infinitely long decimal expansion; for example, 1 divided by 3. If the quotient has a nonterminating decimal expansion and the operation is specified to return an exact result, an ArithmeticException is thrown. Otherwise, the exact result of the division is returned, as done for other operations.

When the _precision setting is not 0, the rules of BigDecimal arithmetic are broadly compatible with selected modes of operation of the arithmetic defined in ANSI X3.274-1996 and ANSI X3.274-1996/AM 1-2000 (section 7.4). Unlike those standards, BigDecimal includes many rounding modes, which were mandatory for division in BigDecimal releases prior to 5. Any conflicts between these ANSI standards and the BigDecimal specification are resolved in favor of BigDecimal.

Since the same numerical value can have different representations (with different scales), the rules of arithmetic and rounding must specify both the numerical result and the scale used in the result's representation.

In general the rounding modes and precision setting determine how operations return results with a limited number of digits when the exact result has more digits (perhaps infinitely many in the case of division and square root) than the number of digits returned.

First, the total number of digits to return is specified by the MathContext's precision setting; this determines the result's precision. The digit count starts from the leftmost nonzero digit of the exact result. The rounding mode determines how any discarded trailing digits affect the returned result.

For all arithmetic operators , the operation is carried out as though an exact intermediate result were first calculated and then rounded to the number of digits specified by the precision setting (if necessary), using the selected rounding mode. If the exact result is not returned, some digit positions of the exact result are discarded. When rounding increases the magnitude of the returned result, it is possible for a new digit position to be created by a carry propagating to a leading &quot;9&quot; digit. For example, rounding the value 999.9 to three digits rounding up would be numerically equal to one thousand, represented as 10010^1. In such cases, the new &quot;1&quot; is the leading digit position of the returned result.

Besides a logical exact result, each arithmetic operation has a preferred scale for representing a result. The preferred scale for each operation is listed in the table below.

<table class="striped" style="text-align:left"> <caption>Preferred Scales for Results of Arithmetic Operations </caption> * <thead> <tr><th scope="col">Operation</th><th scope="col">Preferred Scale of Result</th></tr> </thead> * <tbody> <tr><th scope="row">Add</th><td>max(addend.scale, augend.scale)</td> </tr> * <tr><th scope="row">Subtract</th><td>max(minuend.scale, subtrahend.scale)</td> </tr> * <tr><th scope="row">Multiply</th><td>multiplier.scale + multiplicand.scale</td> </tr> * <tr><th scope="row">Divide</th><td>dividend.scale - divisor.scale</td> </tr> * <tr><th scope="row">Square root</th><td>radicand.scale/2</td> </tr></tbody> * </table> *

These scales are the ones used by the methods which return exact arithmetic results; except that an exact div may have to use a larger scale since the exact result may have more digits. For example, 1/32 is 0.03125.

Before rounding, the scale of the logical exact intermediate result is the preferred scale for that operation. If the exact numerical result cannot be represented in precision digits, rounding selects the set of digits to return and the scale of the result is reduced from the scale of the intermediate result to the least scale which can represent the precision digits actually returned. If the exact result can be represented with at most precision digits, the representation of the result with the scale closest to the preferred scale is returned. In particular, an exactly representable quotient may be represented in fewer than precision digits by removing trailing zeros and decreasing the scale. For example, rounding to three digits using the floor rounding mode, <br></br>

19/100 = 0.19 // integer=19, scale=2 <br></br>

but<br></br>

21/110 = 0.190 // integer=190, scale=3 <br></br>

Note that for plus, minus, and timesLong, the reduction in scale will equal the number of digit positions of the exact result which are discarded. If the rounding causes a carry propagation to create a new high-order digit position, an additional digit of the result is discarded than when no new digit position is created.

Other methods may have slightly different rounding semantics. For example, the result of the pow method using the specified algorithm can occasionally differ from the rounded mathematical result by more than one unit in the last place, one ulp.

Two types of operations are provided for manipulating the scale of a BigDecimal: scaling/rounding operations and decimal point motion operations. Scaling/rounding operations (setScale and round) return a BigDecimal whose value is approximately (or exactly) equal to that of the operand, but whose scale or _precision is the specified value; that is, they increase or decrease the _precision of the stored number with minimal effect on its value. Decimal point motion operations (movePointLeft and movePointRight) return a BigDecimal created from the operand by moving the decimal point a specified distance in the specified direction.

For the sake of brevity and clarity, pseudo-code is used throughout the descriptions of BigDecimal methods. The pseudo-code expression (i + j) is shorthand for "a BigDecimal whose value is that of the BigDecimali added to that of the BigDecimalj." The pseudo-code expression (i == j) is shorthand for "true if and only if the BigDecimali represents the same value as the BigDecimalj." Other pseudo-code expressions are interpreted similarly. Square brackets are used to represent the particular BigInteger and scale pair defining a BigDecimal value; for example [19, 2] is the BigDecimal numerically equal to 0.19 having a scale of 2.

All methods and constructors for this class throw NullPointerException when passed a null object reference for any input parameter.

Author

Josh Bloch

Mike Cowlishaw

Joseph D. Darcy

Sergey V. Kuksenko

Since

1.1

See also

Constructors

BigDecimal
Link copied to clipboard
common
fun BigDecimal(val: Double, mc: MathContext = MathContext.UNLIMITED)
Translates a double into a BigDecimal, with rounding according to the context settings.

Types

Companion
Link copied to clipboard
common
object Companion

Functions

absoluteValue
Link copied to clipboard
common
fun absoluteValue(mc: MathContext): BigDecimal?
Returns a BigDecimal whose value is the absolute value of this BigDecimal, with rounding according to the context settings.
compareTo
Link copied to clipboard
common
open operator override fun compareTo(other: BigDecimal): Int
Compares this BigDecimal with the specified BigDecimal.
div
Link copied to clipboard
common
operator fun div(divisor: BigDecimal): BigDecimal
Returns a BigDecimal whose value is (this / divisor), and whose preferred _scale is (this._scale() - divisor._scale()); if the exact quotient cannot be represented (because it has a non-terminating decimal expansion) an ArithmeticException is thrown.
fun div(divisor: BigDecimal, mc: MathContext): BigDecimal?
Returns a BigDecimal whose value is (this / divisor), with rounding according to the context settings.
divideAndRemainder
Link copied to clipboard
common
fun divideAndRemainder(divisor: BigDecimal): Pair<BigDecimal, BigDecimal>
Returns a two-element BigDecimal array containing the result of divideToIntegralValue followed by the result of remainder on the two operands.
fun divideAndRemainder(divisor: BigDecimal, mc: MathContext): Pair<BigDecimal, BigDecimal>
Returns a two-element BigDecimal array containing the result of divideToIntegralValue followed by the result of remainder on the two operands calculated with rounding according to the context settings.
divideToIntegralValue
Link copied to clipboard
common
fun divideToIntegralValue(divisor: BigDecimal): BigDecimal?
Returns a BigDecimal whose value is the integer part of the quotient (this / divisor) rounded down.
fun divideToIntegralValue(divisor: BigDecimal, mc: MathContext): BigDecimal?
Returns a BigDecimal whose value is the integer part of (this / divisor).
equals
Link copied to clipboard
common
open operator override fun equals(other: Any?): Boolean
Compares this BigDecimal with the specified Object for equality.
hashCode
Link copied to clipboard
common
open override fun hashCode(): Int
Returns the hash code for this BigDecimal.
max
Link copied to clipboard
common
fun max(val: BigDecimal): BigDecimal
Returns the maximum of this BigDecimal and val.
min
Link copied to clipboard
common
fun min(val: BigDecimal): BigDecimal
Returns the minimum of this BigDecimal and val.
minus
Link copied to clipboard
common
operator fun minus(subtrahend: BigDecimal): BigDecimal
Returns a BigDecimal whose value is (this - subtrahend), and whose _scale is max(this._scale(), subtrahend._scale()).
fun minus(subtrahend: BigDecimal, mc: MathContext): BigDecimal
Returns a BigDecimal whose value is (this - subtrahend), with rounding according to the context settings.
movePointLeft
Link copied to clipboard
common
fun movePointLeft(n: Int): BigDecimal
Returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the left.
movePointRight
Link copied to clipboard
common
fun movePointRight(n: Int): BigDecimal
Returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the right.
plus
Link copied to clipboard
common
operator fun plus(augend: BigDecimal?): BigDecimal
Returns a BigDecimal whose value is (this + augend), and whose _scale is max(this._scale(), augend._scale()).
fun plus(augend: BigDecimal?, mc: MathContext): BigDecimal
Returns a BigDecimal whose value is (this + augend), with rounding according to the context settings.
pow
Link copied to clipboard
common
infix fun pow(n: Int): BigDecimal
Returns a BigDecimal whose value is (this<sup>n</sup>), The power is computed exactly, to unlimited _precision.
fun pow(n: Int, mc: MathContext): BigDecimal?
Returns a BigDecimal whose value is (this<sup>n</sup>).
rem
Link copied to clipboard
common
operator fun rem(divisor: BigDecimal): BigDecimal
Returns a BigDecimal whose value is (this % divisor).
fun rem(divisor: BigDecimal, mc: MathContext): BigDecimal
Returns a BigDecimal whose value is (this % divisor), with rounding according to the context settings.
round
Link copied to clipboard
common
fun round(mc: MathContext): BigDecimal?
Returns a BigDecimal rounded according to the MathContext settings.
scaleByPowerOfTen
Link copied to clipboard
common
fun scaleByPowerOfTen(n: Int): BigDecimal
Returns a BigDecimal whose numerical value is equal to (this * 10<sup>n</sup>).
setScale
Link copied to clipboard
common
fun setScale(newScale: Int): BigDecimal
Returns a BigDecimal whose _scale is the specified value, and whose value is numerically equal to this BigDecimal's.
fun setScale(newScale: Int, roundingMode: RoundingMode): BigDecimal
Returns a BigDecimal whose _scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal's unscaled value by the appropriate power of ten to maintain its overall value.
sqrt
Link copied to clipboard
common
fun sqrt(mc: MathContext = MathContext()): BigDecimal
Returns an approximation to the square root of this with rounding according to the context settings.
stripTrailingZeros
Link copied to clipboard
common
fun stripTrailingZeros(): BigDecimal
Returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation.
times
Link copied to clipboard
common
operator fun times(multiplicand: BigDecimal?): BigDecimal
Returns a BigDecimal whose value is (this multiplicand), and whose _scale is (this._scale() + multiplicand._scale()).
fun times(multiplicand: BigDecimal, mc: MathContext): BigDecimal
Returns a BigDecimal whose value is (this multiplicand), with rounding according to the context settings.
toBigInteger
Link copied to clipboard
common
fun toBigInteger(): BigInteger
Converts this BigDecimal to a BigInteger.
toBigIntegerExact
Link copied to clipboard
common
fun toBigIntegerExact(): BigInteger
Converts this BigDecimal to a BigInteger, checking for lost information.
toByte
Link copied to clipboard
common
fun toByte(): Byte
toByteExact
Link copied to clipboard
common
fun toByteExact(): Byte
Converts this BigDecimal to a byte, checking for lost information.
toChar
Link copied to clipboard
common
fun toChar(): Char
toDouble
Link copied to clipboard
common
fun toDouble(): Double
Converts this BigDecimal to a double.
toEngineeringString
Link copied to clipboard
common
fun toEngineeringString(): String
Returns a string representation of this BigDecimal, using engineering notation if an exponent is needed.
toFloat
Link copied to clipboard
common
fun toFloat(): Float
Converts this BigDecimal to a float.
toInt
Link copied to clipboard
common
fun toInt(): Int
Converts this BigDecimal to an int.
toIntExact
Link copied to clipboard
common
fun toIntExact(): Int
Converts this BigDecimal to an int, checking for lost information.
toLong
Link copied to clipboard
common
fun toLong(): Long
Converts this BigDecimal to a long.
toLongExact
Link copied to clipboard
common
fun toLongExact(): Long
Converts this BigDecimal to a long, checking for lost information.
toPlainString
Link copied to clipboard
common
fun toPlainString(): String
Returns a string representation of this BigDecimal without an exponent field.
toShort
Link copied to clipboard
common
fun toShort(): Short
toShortExact
Link copied to clipboard
common
fun toShortExact(): Short
Converts this BigDecimal to a short, checking for lost information.
toString
Link copied to clipboard
common
open override fun toString(): String
Returns the string representation of this BigDecimal, using scientific notation if an exponent is needed.
ulp
Link copied to clipboard
common
fun ulp(): BigDecimal
Returns the size of an ulp, a unit in the last place, of this BigDecimal.
unaryMinus
Link copied to clipboard
common
operator fun unaryMinus(): BigDecimal
Returns a BigDecimal whose value is (-this), and whose _scale is this._scale().
fun unaryMinus(mc: MathContext): BigDecimal?
Returns a BigDecimal whose value is (-this), with rounding according to the context settings.
unaryPlus
Link copied to clipboard
common
operator fun unaryPlus(): BigDecimal
Returns a BigDecimal whose value is (+this), and whose _scale is this._scale().
fun unaryPlus(mc: MathContext): BigDecimal?
Returns a BigDecimal whose value is (+this), with rounding according to the context settings.

Properties

absoluteValue
Link copied to clipboard
common
val absoluteValue: BigDecimal
Returns a BigDecimal whose value is the absolute value of this BigDecimal, and whose _scale is this._scale().
precision
Link copied to clipboard
common
val precision: Int
Returns the _precision of this BigDecimal.
scale
Link copied to clipboard
common
val scale: Int
Returns the _scale of this BigDecimal.
signum
Link copied to clipboard
common
val signum: Int
Returns the _signum function of this BigDecimal.
unscaledValue
Link copied to clipboard
common
val unscaledValue: BigInteger
Returns a BigInteger whose value is the unscaled value of this BigDecimal.

Extensions

toJava
Link copied to clipboard
fun BigDecimal.toJava(): BigDecimal