BigDecimal
About
The BigDecimal
class is designed to handle real numbers with arbitrary precision and scale. Unlike floating-point types (float
and double
), BigDecimal
eliminates rounding errors and ensures precise representation of decimal values. This makes it ideal for computations involving money, tax, and measurements.
Internally, BigDecimal
represents numbers as a combination of:
Unscaled Value: A
BigInteger
representing the number without its decimal point.Scale: An integer indicating the number of digits to the right of the decimal point.
Example:
BigDecimal("123.45")
is stored as:Unscaled Value:
12345
Scale:
2
Features
Arbitrary Precision: Supports numbers with virtually unlimited digits, restricted only by memory.
Immutable:
BigDecimal
objects are immutable, ensuring that any modification creates a new object.Exact Arithmetic: Offers precise control over rounding behavior with
RoundingMode
.Support for Scaling: Provides methods to set and adjust the scale of numbers.
Extensive Arithmetic Operations: Supports addition, subtraction, multiplication, division, modulus, power, and more.
Integration with MathContext: Allows control over precision and rounding for calculations.
How BigDecimal Differs from Primitive Types ?
Feature
Primitive Types (float
, double
)
BigDecimal
Precision
Limited by IEEE 754 (approx. 7–16 digits)
Arbitrary precision
Accuracy
Prone to rounding and representation errors
Exact representation
Mutability
Mutable (values can change)
Immutable
Operations
Basic arithmetic
Advanced (e.g., scaling, rounding)
Performance
Faster (hardware-supported operations)
Slower (software-based)
Thread-Safety
Not inherently thread-safe
Thread-safe
How Immutability Works in BigDecimal
BigDecimal
is immutable, meaning its state cannot be changed once created. Any arithmetic or scale-altering operation returns a new BigDecimal
object.
Mechanisms Ensuring Immutability
Final Fields: Key fields (
intCompact
,intVal
,scale
) are declaredfinal
and cannot be reassigned after initialization.Defensive Copies: When constructors or methods accept mutable objects (like arrays),
BigDecimal
creates a defensive copy to prevent external modification.Return New Instances: Arithmetic methods (
add
,multiply
, etc.) return new objects without altering the original.
Example of Immutability
When and Why to Use BigDecimal
When?
When calculations demand exact precision, such as:
Financial transactions
Scientific measurements
Tax calculations
Why?
Avoids Rounding Errors: Unlike floating-point types,
BigDecimal
accurately represents decimal numbers without approximation errors.Precision Control: Allows fine-tuned control over scale and rounding.
Thread Safety: Safe to use in multi-threaded environments.
Creating a BigDecimal Object
We can create a BigDecimal
object using:
String Constructor (Preferred):
This avoids floating-point conversion errors.
Using
valueOf
:Converts
double
to aBigDecimal
while preserving accuracy.
From Integers or Longs:
Operations on BigDecimal
Arithmetic Operations:
add(BigDecimal)
– Additionsubtract(BigDecimal)
– Subtractionmultiply(BigDecimal)
– Multiplicationdivide(BigDecimal, RoundingMode)
– Division with specified rounding mode
Scaling and Rounding:
setScale(int scale, RoundingMode roundingMode)
round(MathContext mc)
Comparison:
compareTo(BigDecimal)
– Compares twoBigDecimal
values.
Conversion:
toString()
,toPlainString()
,doubleValue()
,longValue()
, etc.
Mathematical Operations:
abs()
,negate()
,pow(int n)
Example
Limitations of BigDecimal
Performance: Slower than primitive types due to software-based implementation.
Complex Syntax: Operations require explicit method calls, unlike simple operators for primitive types.
Memory Overhead: Larger memory footprint compared to primitive types.
Overhead of Immutability: Frequent object creation can lead to increased garbage collection.
Use Cases
Financial Applications: Precise currency calculations, avoiding rounding errors.
Scientific Calculations: Modeling data that requires high precision.
Tax and Interest Rate Calculations: Where fractions of pennies or percentage points matter.
Cryptography: Accurate mathematical computations for secure algorithms.
Last updated
Was this helpful?