Perform fixed-point arithmetic with decimal4j
masterdecimal4j provides fixed-point arithmetic using unscaled long values, supporting between 0 and 18 decimal places. The scale is determined by the specific type used (e.g., Decimal2f for 2 decimal places, Decimal18f for 18).
Key Features
- Scale Management: The result of an operation usually inherits the scale of the primary operand.
- Rounding: Supports all
java.math.RoundingModeoptions. The default rounding mode isHALF_UP. - Overflow: Provides options to throw an exception when arithmetic overflow occurs.
- Efficiency: Offers
MutableDecimalfor chained operations and aDecimalArithmeticAPI for zero-garbage computations using unscaled long values.
// Example: Interest Calculation
Decimal2f principal = Decimal2f.valueOf(9500);
Decimal3f rate = Decimal3f.valueOf(0.067);
Decimal2f time = Decimal2f.valueOf(1).divide(4);
Decimal2f interest = principal.multiplyBy(rate.multiplyExact(time));
System.out.println("First quarter interest: $" + interest);
// Example: Using specific RoundingMode
Decimal2f down = radius.multiplyBy(PI.multiply(2), RoundingMode.DOWN);