### Run Build with All Test Cases Source: https://github.com/tools4j/decimal4j/wiki/Test-Coverage Customize test case selection, impacting special cases and random test counts, by setting the 'testCases' system property. This example runs with all available test cases. ```bash gradle clean build jacocoTestReport -DtestCases=ALL ``` -------------------------------- ### Using ScaleMetrics and Scales Source: https://context7.com/tools4j/decimal4j/llms.txt Retrieve scale metrics for a specific scale, access arithmetic configurations, and perform unscaled long operations. Demonstrates how to get all available scales and their factors. ```java import org.decimal4j.scale.ScaleMetrics; import org.decimal4j.scale.Scales; import org.decimal4j.api.DecimalArithmetic; import java.math.RoundingMode; public class ScaleMetricsExample { public static void main(String[] args) { // Retrieve scale metrics for scale 6 ScaleMetrics sm6 = Scales.getScaleMetrics(6); System.out.println("Scale: " + sm6.getScale()); // 6 System.out.println("Scale factor: " + sm6.getScaleFactor()); // 1000000 // Get various arithmetic configurations DecimalArithmetic defaultArith = sm6.getDefaultArithmetic(); // HALF_UP, UNCHECKED DecimalArithmetic floorArith = sm6.getArithmetic(RoundingMode.FLOOR); DecimalArithmetic checkedArith = sm6.getCheckedArithmetic(RoundingMode.HALF_UP); // throws on overflow // Unscaled long operations via ScaleMetrics helpers (compiler-optimized) long val = 3_141593L; // represents 3.141593 at scale 6 long doubled = sm6.multiplyByScaleFactor(val); // internal: val * 10^6 System.out.println("Scale factor multiply: " + doubled); // Get all available scales for (ScaleMetrics sm : Scales.VALUES) { System.out.println("Scale " + sm.getScale() + " factor = " + sm.getScaleFactor()); } // Scale 0 factor = 1, Scale 1 factor = 10, ..., Scale 18 factor = 1000000000000000000 } } ``` -------------------------------- ### Decimal Multiplication Examples Source: https://context7.com/tools4j/decimal4j/llms.txt Demonstrates same-scale, cross-scale, and exact multiplication using `multiply()`, `multiplyBy()`, and `multiplyExact().by()`. Ensure correct scale handling and rounding modes for desired precision. ```java import org.decimal4j.immutable.Decimal2f; import org.decimal4j.immutable.Decimal3f; import org.decimal4j.immutable.Decimal5f; import org.decimal4j.immutable.Decimal6f; import java.math.RoundingMode; public class MultiplyExamples { public static void main(String[] args) { Decimal2f a = Decimal2f.valueOf(4); Decimal2f b = Decimal2f.valueOf(1.5); Decimal3f c = Decimal3f.valueOf(0.125); Decimal3f d = Decimal3f.valueOf(0.5); // Same-scale multiply — result rounded to receiver's scale System.out.println("a*b = " + a.multiply(b)); // 6.00 System.out.println("c*d = " + c.multiply(d)); // 0.063 System.out.println("c*d DOWN = " + c.multiply(d, RoundingMode.DOWN)); // 0.062 // Cross-scale: result keeps receiver's scale System.out.println("a*c = " + a.multiplyBy(c)); // 0.50 (Decimal2f) System.out.println("b*c = " + b.multiplyBy(c)); // 0.19 (Decimal2f) // Exact multiply: scale = scale(c) + scale(d) = 3+3 = 6 Decimal6f exactCD = c.multiplyExact().by(d); // 0.062500 System.out.println("c*d exact = " + exactCD); // Exact multiply with mixed scales: 2+3 = 5 Decimal5f exactAD = a.multiplyExact().by(d); // 2.00000 System.out.println("a*d exact = " + exactAD); } } ``` -------------------------------- ### Run Build with All Scales Source: https://github.com/tools4j/decimal4j/wiki/Test-Coverage Override the default scales for a specific test variant by setting the 'testScales' system property. This example runs the STANDARD test variant with all scales. ```bash gradle clean build jacocoTestReport -DtestScales=ALL ``` -------------------------------- ### Immutable Decimal Type Examples in Java Source: https://context7.com/tools4j/decimal4j/llms.txt Demonstrates basic creation, interest calculation, rounding modes, type conversion, scale changes, and integral/fractional part extraction using immutable Decimal types. Ensure correct imports for Decimal classes and RoundingMode. ```java import org.decimal4j.immutable.Decimal2f; import org.decimal4j.immutable.Decimal3f; import org.decimal4j.immutable.Decimal18f; import java.math.RoundingMode; public class ImmutableExamples { public static void main(String[] args) { // --- Basic creation --- Decimal2f price = Decimal2f.valueOf(9500); // 9500.00 Decimal3f rate = Decimal3f.valueOf(0.067); // 0.067 Decimal2f quarter = Decimal2f.valueOf(1).divide(4); // 0.25 // --- Interest calculation --- // multiplyExact yields Decimal5f (2+3 fractional digits) // multiplyBy rescales result back to Decimal2f Decimal2f interest = price.multiplyBy(rate.multiplyExact(quarter)); System.out.println("Interest: $" + interest); // Interest: $159.13 // --- Rounding modes --- Decimal18f PI = Decimal18f.valueOf(Math.PI); Decimal2f r = Decimal2f.valueOf(5); Decimal2f circ = r.multiplyBy(PI.multiply(2)); Decimal2f down = r.multiplyBy(PI.multiply(2), RoundingMode.DOWN); System.out.println("Circumference ~" + circ + "m"); // ~31.42m System.out.println("Circumference >" + down + "m"); // >31.41m // --- Type conversion --- long lv = price.longValue(); // 9500 double dv = price.doubleValue(); // 9500.0 int iv = price.intValue(); // 9500 // --- Checked conversion (throws if fractional part exists) --- try { long exact = Decimal2f.valueOf(9.50).longValueExact(); // throws } catch (ArithmeticException e) { System.out.println("Has fractional part: " + e.getMessage()); } // --- Scale change --- // scale(int) returns Decimal at runtime; scale throws if overflow var as3 = price.scale(3); // 9500.000 (Decimal3f at runtime) var as1 = price.scale(1, RoundingMode.HALF_UP); // 9500.0 // --- Integral and fractional parts --- Decimal2f val = Decimal2f.valueOf(9.75); Decimal2f intP = val.integralPart(); // 9.00 Decimal2f frac = val.fractionalPart(); // 0.75 System.out.println("Integral: " + intP + ", Fractional: " + frac); // --- sqrt (high-precision example) --- System.out.println("sqrt(2) = " + Decimal18f.TWO.sqrt()); // sqrt(2) = 1.414213562373095049 } } ``` -------------------------------- ### Decimal Division Examples Source: https://context7.com/tools4j/decimal4j/llms.txt Illustrates various division methods including default rounding, explicit rounding modes, division by long/double, cross-scale division, and reciprocal calculation. Note the default rounding mode is HALF_UP. ```java import org.decimal4j.immutable.Decimal4f; import org.decimal4j.immutable.Decimal2f; import java.math.RoundingMode; public class DivideExamples { public static void main(String[] args) { Decimal4f a = Decimal4f.valueOf(10); Decimal4f b = Decimal4f.valueOf(3); // Default rounding (HALF_UP) System.out.println("10/3 = " + a.divide(b)); // 3.3333 System.out.println("10/3 DOWN = " + a.divide(b, RoundingMode.DOWN)); // 3.3333 // Divide by long System.out.println("10/4 = " + a.divideByLong(4)); // 2.5000 // Divide by double System.out.println("10/2.5 = " + a.divide(2.5)); // 4.0000 // Cross-scale division Decimal2f result = Decimal2f.valueOf(7.50).divideBy(Decimal4f.valueOf(2.5000)); System.out.println("7.50 / 2.5000 = " + result); // 3.00 // Reciprocal (1/this) Decimal4f inv = Decimal4f.valueOf(4).reciprocal(); // 0.2500 System.out.println("1/4 = " + inv); } } ``` -------------------------------- ### Example: Rounding Doubles with DoubleRounder Source: https://github.com/tools4j/decimal4j/wiki/DoubleRounder-Utility-(Deprecated) Demonstrates various rounding scenarios using DoubleRounder with different precisions and rounding modes. Note that DoubleRounder is deprecated and may produce unexpected results. ```java public class RoundDouble { public static void main(String[] args) { final double oneSeventh = 1.0 / 7.0; final double twoThirds = 2.0 / 3.0; System.out.println(oneSeventh); System.out.println(twoThirds); double rounded17 = DoubleRounder.round(oneSeventh, 3); double rounded23 = DoubleRounder.round(twoThirds, 3); System.out.println(rounded17); System.out.println(rounded23); System.out.println(DoubleRounder.round(oneSeventh, 3, RoundingMode.DOWN)); System.out.println(DoubleRounder.round(twoThirds, 3, RoundingMode.DOWN)); System.out.println(DoubleRounder.round(oneSeventh, 10)); System.out.println(DoubleRounder.round(twoThirds, 10)); System.out.println(DoubleRounder.round(oneSeventh, 15)); System.out.println(DoubleRounder.round(twoThirds, 15)); final double oneTenthPow18 = Math.pow(0.1, 18); System.out.println(); System.out.println(oneTenthPow18); System.out.println(DoubleRounder.round(oneTenthPow18, 18)); } } ``` -------------------------------- ### Dynamic Decimal Creation with DecimalFactory Source: https://context7.com/tools4j/decimal4j/llms.txt Utilize DecimalFactory to create ImmutableDecimal and MutableDecimal instances when the scale is determined at runtime. Shows how to get a factory for a specific scale and convert between mutable and immutable types. ```java import org.decimal4j.api.ImmutableDecimal; import org.decimal4j.api.MutableDecimal; import org.decimal4j.factory.DecimalFactory; import org.decimal4j.factory.Factories; public class FactoryExample { public static void main(String[] args) { // Get factory for scale 4 at runtime DecimalFactory factory = Factories.getDecimalFactory(4); ImmutableDecimal immVal = factory.valueOf(3.1416); MutableDecimal mutVal = factory.newMutable(); mutVal.set(2.7183); System.out.println("Immutable: " + immVal); // 3.1416 System.out.println("Mutable: " + mutVal); // 2.7183 // Convert between mutable and immutable ImmutableDecimal snapshot = mutVal.toImmutableDecimal(); MutableDecimal working = immVal.toMutableDecimal(); // Generic factory from a Decimal instance DecimalFactory sameFactory = immVal.getFactory(); ImmutableDecimal copy = sameFactory.valueOf(immVal.doubleValue()); System.out.println("Copy: " + copy); // 3.1416 } } ``` -------------------------------- ### Decimal Power Operations Examples Source: https://context7.com/tools4j/decimal4j/llms.txt Shows how to compute square roots, squares, and powers of decimal numbers. `sqrt()` and `square()` respect the receiver's scale with HALF_UP rounding, while `pow(int)` raises to an integer power. ```java import org.decimal4j.immutable.Decimal17f; import org.decimal4j.immutable.Decimal18f; import org.decimal4j.immutable.Decimal4f; public class PowerExamples { public static void main(String[] args) { // Square root System.out.println("sqrt(2) = " + Decimal18f.TWO.sqrt()); // sqrt(2) = 1.414213562373095049 System.out.println("sqrt(2) = " + Math.sqrt(2)); // sqrt(2) = 1.4142135623730951 (double loses last digit) // Square Decimal4f x = Decimal4f.valueOf(1.5); System.out.println("1.5^2 = " + x.square()); // 2.2500 // Power Decimal4f two = Decimal4f.valueOf(2); System.out.println("2^10 = " + two.pow(10)); // 1024.0000 System.out.println("2^-3 = " + two.pow(-3)); // 0.1250 // Gauss-Legendre PI approximation (3 iterations) Decimal17f a = Decimal17f.ONE; Decimal17f b = Decimal17f.TWO.sqrt().shiftRight(1); // sqrt(2)/2 Decimal17f t = Decimal17f.ONE.divide(4); Decimal17f p = Decimal17f.ONE; for (int i = 0; i < 3; i++) { Decimal17f an = a.avg(b); Decimal17f bn = a.multiply(b).sqrt(); Decimal17f tn = t.subtract(p.multiply(a.subtract(an).square())); Decimal17f pn = p.shiftLeft(1); a = an; b = bn; t = tn; p = pn; } System.out.println("PI = " + a.add(b).square().divide(t).shiftRight(2)); // PI = 3.14159265358979315 } } ``` -------------------------------- ### Zero-Garbage Primitive Arithmetic with `DecimalArithmetic` Source: https://context7.com/tools4j/decimal4j/llms.txt Obtain `DecimalArithmetic` for a given scale and perform arithmetic operations without object allocation. Demonstrates conversion from various types to unscaled longs, printing values, and deriving arithmetic instances with different rounding modes or scales. Includes an example of overflow-checked arithmetic. ```java import org.decimal4j.api.DecimalArithmetic; import org.decimal4j.scale.ScaleMetrics; import org.decimal4j.scale.Scales; import java.math.RoundingMode; public class ZeroGarbageExample { public static void main(String[] args) throws Exception { // Obtain arithmetic for scale=3 with default (HALF_UP) rounding ScaleMetrics scale3 = Scales.getScaleMetrics(3); DecimalArithmetic arith = scale3.getDefaultArithmetic(); // Convert inputs to unscaled longs (zero allocation) long a = arith.fromLong(4); // 4000 (4 * 10^3) long b = arith.fromDouble(1.5); // 1500 long c = arith.fromDouble(0.125); // 125 long d = arith.fromUnscaled(1, arith.getScale()); // 1 (= 0.001) // Print values without allocating strings to heap System.out.print("a = "); arith.toString(a, System.out); System.out.println(); System.out.print("b = "); arith.toString(b, System.out); System.out.println(); // a = 4.000, b = 1.500 // Arithmetic (zero garbage) long sumAB = arith.add(a, b); // 5500 (5.500) long prodAB = arith.multiply(a, b); // 6000 (6.000) long divAB = arith.divide(a, b); // 2667 (2.667) long avgCD = arith.avg(c, d); // 63 (0.063) System.out.print("a+b = "); arith.toString(sumAB, System.out); System.out.println(); System.out.print("a*b = "); arith.toString(prodAB, System.out); System.out.println(); System.out.print("a/b = "); arith.toString(divAB, System.out); System.out.println(); // Derive arithmetic with different rounding (still zero garbage) DecimalArithmetic upArith = arith.deriveArithmetic(RoundingMode.UP); DecimalArithmetic downArith = arith.deriveArithmetic(RoundingMode.DOWN); System.out.print("UP avg(b,c) = "); arith.toString(upArith.avg(b, c), System.out); System.out.println(); System.out.print("DOWN avg(b,c) = "); arith.toString(downArith.avg(b, c), System.out); System.out.println(); // UP avg(b,c) = 0.813, DOWN avg(b,c) = 0.812 // Derive arithmetic with different scale (e.g. round to 2 decimal places) DecimalArithmetic arith2 = arith.deriveArithmetic(2); long rounded = arith.round(c, 2); // 130 at scale3 = 0.130 long scaled = arith2.fromUnscaled(c, arith.getScale()); // 13 at scale2 = 0.13 System.out.print("round(c,2) at scale3 = "); arith.toString(rounded, System.out); System.out.println(); System.out.print("scale(c) to scale2 = "); arith2.toString(scaled, System.out); System.out.println(); // Overflow-checked arithmetic DecimalArithmetic checked = scale3.getCheckedArithmetic(RoundingMode.HALF_UP); try { long overflow = checked.multiply(Long.MAX_VALUE / 1000, arith.fromLong(2)); } catch (ArithmeticException e) { System.out.println("Overflow detected: " + e.getMessage()); } } } ``` -------------------------------- ### Run All Benchmarks with Gradle Source: https://github.com/tools4j/decimal4j/wiki/Performance Execute the complete performance test suite using Gradle. Note that this process can take approximately 3 hours. ```bash gradle jmh ``` -------------------------------- ### Run All JMH Benchmarks Source: https://context7.com/tools4j/decimal4j/llms.txt Initiates all JMH benchmarks for decimal4j. This process can take approximately 3 hours to complete. ```bash ./gradlew jmh ``` -------------------------------- ### Compare Decimal values using compareTo() and predicates Source: https://context7.com/tools4j/decimal4j/llms.txt Demonstrates comparing Decimal values using the `Comparable` interface's `compareTo()` method and convenience predicates like `isGreaterThan()`, `isLessThan()`, `isEqualTo()`, `isZero()`, `isPositive()`, and `isNegative()`. Also shows `min()` and `max()` methods. ```java import org.decimal4j.immutable.Decimal2f; public class CompareExamples { public static void main(String[] args) { Decimal2f a = Decimal2f.valueOf(5.00); Decimal2f b = Decimal2f.valueOf(3.50); Decimal2f zero = Decimal2f.ZERO; System.out.println("a > b : " + a.isGreaterThan(b)); // true System.out.println("b < a : " + b.isLessThan(a)); // true System.out.println("a == 5: " + a.isEqualTo(Decimal2f.valueOf(5))); // true System.out.println("zero? : " + zero.isZero()); // true System.out.println("positive: " + a.isPositive()); // true System.out.println("negative: " + b.negate().isNegative()); // true // Comparable interface int cmp = a.compareTo(b); // > 0 System.out.println("compareTo: " + cmp); // min / max (ImmutableDecimal) Decimal2f min = a.min(b); // 3.50 Decimal2f max = a.max(b); // 5.00 System.out.println("min=" + min + " max=" + max); } } ``` -------------------------------- ### Run All Benchmarks from Command Line Source: https://github.com/tools4j/decimal4j/wiki/Performance Execute all JMH benchmarks from the command line using the JMH runner class. This is an alternative to using Gradle for running the full suite. ```bash java -cp build/libs/decimal4j-1.0.1-jmh.jar org.decimal4j.jmh.JmhRunner ``` -------------------------------- ### Calculate Interest with Decimal2f and Decimal3f Source: https://github.com/tools4j/decimal4j/blob/master/README.md Demonstrates calculating simple interest using Decimal2f for principal and time, and Decimal3f for the rate. Imports are not shown but would be required. ```java public class Interest { public static void main(String[] args) { 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); } } ``` -------------------------------- ### Run Single Test from Command Line Source: https://github.com/tools4j/decimal4j/wiki/Performance Execute a single JMH benchmark test from the command line using the compiled JAR file. Ensure the classpath includes the JMH JAR. ```bash java -cp build/libs/decimal4j-1.0.1-jmh.jar org.decimal4j.jmh.AddBenchmark ``` -------------------------------- ### Perform Decimal Addition with Same and Different Scales Source: https://github.com/tools4j/decimal4j/wiki/Examples Illustrates addition of Decimal2f and Decimal3f values, showing results with same scale and different scales using HALF_UP and UNNECESSARY rounding modes. Imports are not shown. ```java public class Add { public static void main(String[] args) { Decimal2f a = Decimal2f.valueOf(4); Decimal2f b = Decimal2f.valueOf(1.5); Decimal3f c = Decimal3f.valueOf(0.125); Decimal3f d = Decimal3f.valueOf(0.5); System.out.println("ADD: values with same scale"); Decimal2f sumAB = a.add(b); Decimal3f sumCD = c.add(d); System.out.println("a+b = " + sumAB); System.out.println("c+d = " + sumCD); System.out.println("ADD: values with different scales"); Decimal2f sumAC = a.add(c, RoundingMode.HALF_UP); Decimal3f sumCA = c.add(a, RoundingMode.UNNECESSARY); System.out.println("a+c = " + sumAC); System.out.println("c+a = " + sumCA); } } ``` -------------------------------- ### Compile JMH JAR File Source: https://github.com/tools4j/decimal4j/wiki/Performance Compile the JMH JAR file, which is a prerequisite for running individual benchmarks from the command line. ```bash gradle jmhJar ``` -------------------------------- ### Handling Arithmetic Overflow with OverflowMode and TruncationPolicy Source: https://context7.com/tools4j/decimal4j/llms.txt Demonstrates how arithmetic operations behave with the default unchecked overflow mode and how to enable checked overflow exceptions using OverflowMode.CHECKED or TruncationPolicy. Shows primitive checked overflow handling. ```java import org.decimal4j.immutable.Decimal2f; import org.decimal4j.truncate.OverflowMode; import org.decimal4j.truncate.TruncationPolicy; import org.decimal4j.truncate.CheckedRounding; import java.math.RoundingMode; public class OverflowExample { public static void main(String[] args) { Decimal2f max = Decimal2f.valueOf(Long.MAX_VALUE / 100); // near max value // Unchecked (default): silently wraps on overflow Decimal2f silent = max.add(max); System.out.println("Unchecked overflow result: " + silent); // wrapped, no exception // Checked: throws ArithmeticException try { Decimal2f checked = max.add(max, OverflowMode.CHECKED); } catch (ArithmeticException e) { System.out.println("Checked overflow caught: " + e.getMessage()); } // TruncationPolicy bundles RoundingMode + OverflowMode TruncationPolicy policy = CheckedRounding.HALF_UP; // checked + HALF_UP try { Decimal2f result = max.add(max, policy); } catch (ArithmeticException e) { System.out.println("Policy overflow caught: " + e.getMessage()); } // Using DecimalArithmetic with checked overflow import org.decimal4j.scale.Scales; var checkedArith = Scales.getScaleMetrics(2).getCheckedArithmetic(RoundingMode.HALF_UP); long uMax = checkedArith.fromLong(Long.MAX_VALUE / 100); try { checkedArith.add(uMax, uMax); } catch (ArithmeticException e) { System.out.println("Primitive checked overflow: " + e.getMessage()); } } } ``` -------------------------------- ### Decimal.compareTo() and Predicates Source: https://context7.com/tools4j/decimal4j/llms.txt Provides methods for comparing Decimal values, including implementing the Comparable interface and offering convenience predicates for common checks. ```APIDOC ## `Decimal.compareTo()` / `isZero()` / `isPositive()` / `isNegative()` — Comparison `Decimal` implements `Comparable>`. Convenience predicates `isZero()`, `isOne()`, `isPositive()`, `isNegative()`, `isEqualTo()`, `isLessThan()`, `isGreaterThan()` are also available. ### Method Signatures `int compareTo(Decimal other)` `boolean isZero()` `boolean isOne()` `boolean isPositive()` `boolean isNegative()` `boolean isEqualTo(Decimal decimal)` `boolean isLessThan(Decimal decimal)` `boolean isGreaterThan(Decimal decimal)` `Decimal min(Decimal other)` `Decimal max(Decimal other)` ### Example ```java import org.decimal4j.immutable.Decimal2f; Decimal2f a = Decimal2f.valueOf(5.00); Decimal2f b = Decimal2f.valueOf(3.50); Decimal2f zero = Decimal2f.ZERO; System.out.println("a > b : " + a.isGreaterThan(b)); // true System.out.println("b < a : " + b.isLessThan(a)); // true System.out.println("a == 5: " + a.isEqualTo(Decimal2f.valueOf(5))); // true System.out.println("zero? : " + zero.isZero()); // true System.out.println("positive: " + a.isPositive()); // true System.out.println("negative: " + b.negate().isNegative()); // true // Comparable interface int cmp = a.compareTo(b); // > 0 System.out.println("compareTo: " + cmp); // min / max (ImmutableDecimal) Decimal2f min = a.min(b); // 3.50 Decimal2f max = a.max(b); // 5.00 System.out.println("min=" + min + " max=" + max); ``` ``` -------------------------------- ### Run Single Test from IDE Source: https://github.com/tools4j/decimal4j/wiki/Performance Execute a single JMH benchmark test directly from your IDE. Replace 'AddBenchmark' with the specific benchmark class name you wish to run. ```java java org.decimal4j.jmh.AddBenchmark ``` -------------------------------- ### Compile JMH Fat-Jar for decimal4j Source: https://context7.com/tools4j/decimal4j/llms.txt Compiles the JMH fat-jar, which is necessary for running the performance benchmarks. ```bash ./gradlew jmhJar ``` -------------------------------- ### MutableDecimal Operations Source: https://context7.com/tools4j/decimal4j/llms.txt Demonstrates the usage of MutableDecimal for in-place operations and method chaining, suitable for minimizing allocations in performance-critical scenarios. It also shows how to convert mutable decimals to immutable ones. ```APIDOC ## Mutable Decimal Types (`MutableDecimal`) `MutableDecimal` instances modify internal state in-place and return `this`, enabling efficient method chaining. They are NOT thread-safe. Use them when allocations must be minimized over a series of operations (e.g., running statistics). ### Example Usage ```java import org.decimal4j.mutable.MutableDecimal10f; import org.decimal4j.immutable.Decimal10f; import java.util.Random; public class MutableExamples { private static final Random RND = new Random(42); private static final int N = 10_000; public static void main(String[] args) { // --- Mean and variance via mutable chaining --- MutableDecimal10f mean = new MutableDecimal10f(); MutableDecimal10f var = new MutableDecimal10f(); Decimal10f expMean = Decimal10f.valueOf(0); for (int i = 0; i < N; i++) { double v = RND.nextGaussian(); mean.add(v); // accumulate sum var.addSquared(expMean.subtract(v)); // accumulate sum of squares } // divide in-place, returns this System.out.println("Mean: " + mean.divide(N)); // ~0.0... System.out.println("Variance: " + var.divide(N)); // ~1.0... System.out.println("StdDev: " + var.sqrt()); // ~1.0... // --- Explicit set methods --- MutableDecimal10f m = new MutableDecimal10f(); m.setZero(); // 0.0000000000 m.setOne(); // 1.0000000000 m.set(3.14159); // 3.1415900000 m.add(1).multiply(2).subtract(1); // chained: (3.14159 + 1) * 2 - 1 = 7.28318 // --- Conversion to immutable --- Decimal10f immutable = m.toImmutableDecimal(); // snapshot, thread-safe copy System.out.println("Immutable snapshot: " + immutable); } } ``` ``` -------------------------------- ### Rounding and Scale Conversion with Decimal.round() and Decimal.scale() Source: https://context7.com/tools4j/decimal4j/llms.txt Demonstrates rounding to a specified number of decimal places while maintaining scale, and changing the scale of a Decimal value. Supports custom rounding modes and negative precision for rounding to thousands. ```java import org.decimal4j.immutable.Decimal6f; import org.decimal4j.immutable.Decimal2f; import java.math.RoundingMode; public class RoundScaleExamples { public static void main(String[] args) { Decimal6f val = Decimal6f.valueOf(3.141593); // round to 2 decimal places — scale stays 6, trailing digits zeroed System.out.println("round to 2: " + val.round(2)); // 3.140000 System.out.println("round to 2 DOWN: " + val.round(2, RoundingMode.DOWN)); // 3.140000 // round to 0 decimal places (integer rounding) System.out.println("round to 0: " + val.round(0)); // 3.000000 // scale(int) changes actual scale of the returned Decimal Decimal2f scaled = (Decimal2f) val.scale(2); // 3.14 (Decimal2f) System.out.println("scaled to 2: " + scaled); // scale with rounding mode var scaledUp = val.scale(2, RoundingMode.CEILING); // 3.15 System.out.println("scaled to 2 CEILING: " + scaledUp); // Negative precision — round to thousands Decimal6f big = Decimal6f.valueOf(123456.789000); System.out.println("round to -3: " + big.round(-3)); // 123000.000000 } } ``` -------------------------------- ### Run a Single JMH Benchmark Source: https://context7.com/tools4j/decimal4j/llms.txt Executes a specific JMH benchmark, such as the 'Add' benchmark, to measure performance for a particular operation. ```bash java -cp build/libs/decimal4j-1.0.3-jmh.jar org.decimal4j.jmh.AddBenchmark ``` -------------------------------- ### Add decimal4j Dependency to Gradle Project Source: https://github.com/tools4j/decimal4j/blob/master/README.md Add this line to your Gradle project's build script to include the decimal4j library. ```gradle compile 'org.decimal4j:decimal4j:1.0.3' ``` -------------------------------- ### Decimal.sqrt(), Decimal.square(), Decimal.pow() Source: https://context7.com/tools4j/decimal4j/llms.txt Performs power operations including square root, squaring, and raising to an integer power. ```APIDOC ## `Decimal.sqrt()` / `Decimal.square()` / `Decimal.pow()` — Power Operations `sqrt()` computes the square root. `square()` computes this² (result has same scale). `pow(int)` raises to an integer power. All respect the receiver's scale with HALF_UP rounding. ### Method `sqrt()` `square()` `pow(int)` ### Description Calculates the square root, square, or integer power of a Decimal number. These operations maintain the receiver's scale and use `HALF_UP` rounding where applicable. ### Request Example ```java // Square root Decimal18f.TWO.sqrt(); // Square Decimal4f x = Decimal4f.valueOf(1.5); x.square(); // Power Decimal4f two = Decimal4f.valueOf(2); two.pow(10); two.pow(-3); ``` ### Response #### Success Response - **Decimal** - The result of the power operation. ``` -------------------------------- ### Zero Garbage Decimal Arithmetic Operations Source: https://github.com/tools4j/decimal4j/wiki/DecimalArithmetic-API Demonstrates various arithmetic operations like addition, averaging, and rounding using the DecimalArithmetic API. It shows how to initialize DecimalArithmetic with specific scale metrics and derive new arithmetic instances with different rounding modes or scales. ```java public class ZeroGarbage { public static void main(String[] args) throws IOException { ScaleMetrics scale3 = Scales.getScaleMetrics(3); DecimalArithmetic arith = scale3.getDefaultArithmetic(); long a = arith.fromLong(4); long b = arith.fromDouble(1.5); long c = arith.fromDouble(0.125); long d = arith.fromUnscaled(1, arith.getScale()); System.out.println("ZERO GARBAGE: print values"); System.out.print("a = ");arith.toString(a, System.out); System.out.println(); System.out.print("b = ");arith.toString(b, System.out); System.out.println(); System.out.print("c = ");arith.toString(c, System.out); System.out.println(); System.out.print("d = ");arith.toString(d, System.out); System.out.println(); System.out.println(); System.out.println("ZERO GARBAGE: add values"); long sumAB = arith.add(a, b); long sumCD = arith.add(c, d); System.out.print("a+b = ");arith.toString(sumAB, System.out); System.out.println(); System.out.print("c+d = ");arith.toString(sumCD, System.out); System.out.println(); System.out.println(); System.out.println("ZERO GARBAGE: calculate average"); long avgAB = arith.avg(a, b); long avgCD = arith.avg(c, d); long avgABCD = arith.divideByLong(arith.add(sumAB, sumCD), 4); System.out.print("(a+b)/2 = ");arith.toString(avgAB, System.out); System.out.println(); System.out.print("(c+d)/2 = ");arith.toString(avgCD, System.out); System.out.println(); System.out.print("(a+b+c+d)/4 = ");arith.toString(avgABCD, System.out); System.out.println(); System.out.println(); System.out.println("ZERO GARBAGE: round up/down"); long avgBCdup = arith.deriveArithmetic(RoundingMode.UP).avg(b, c); long avgBCdown = arith.deriveArithmetic(RoundingMode.DOWN).avg(b, c); System.out.print("UP: (b+c)/2 = ");arith.toString(avgBCdup, System.out); System.out.println(); System.out.print("DOWN: (b+c)/2 = ");arith.toString(avgBCdown, System.out); System.out.println(); System.out.println(); System.out.println("ZERO GARBAGE: round to 2 decimal places"); DecimalArithmetic arith2 = arith.deriveArithmetic(2); long rounded = arith.round(c, 2); long scaled = arith2.fromUnscaled(c, arith.getScale()); System.out.print("round(c,2) = ");arith.toString(rounded, System.out); System.out.println(); System.out.print("scale(c,2) = ");arith2.toString(scaled, System.out); System.out.println(); } } ``` -------------------------------- ### Multiply/Divide by Powers of 10 with Decimal.shiftLeft() and Decimal.shiftRight() Source: https://context7.com/tools4j/decimal4j/llms.txt Efficiently multiplies a Decimal by 10ⁿ using `shiftLeft(n)` and divides by 10ⁿ using `shiftRight(n)`. `shiftRight` applies HALF_UP rounding by default. ```java import org.decimal4j.immutable.Decimal4f; public class ShiftExamples { public static void main(String[] args) { Decimal4f val = Decimal4f.valueOf(1.2345); System.out.println("shift left 1: " + val.shiftLeft(1)); // 12.3450 System.out.println("shift left 2: " + val.shiftLeft(2)); // 123.4500 System.out.println("shift right 1: " + val.shiftRight(1)); // 0.1235 (HALF_UP) System.out.println("shift right 2: " + val.shiftRight(2)); // 0.0123 // Shift right is equivalent to dividing by power of 10 Decimal4f half = Decimal4f.TWO.shiftRight(1); // 0.2000 == 2 / 10 System.out.println("shiftRight(1) of 2: " + half); } } ``` -------------------------------- ### Decimal.add() - Addition Source: https://context7.com/tools4j/decimal4j/llms.txt Explains how to add two Decimal values. Supports same-scale addition directly and cross-scale addition with a specified rounding mode. Also covers adding long values and doubles, and overflow-checked addition. ```APIDOC ## `Decimal.add()` — Addition `add(Decimal)` adds two Decimal values of the same or different scales. Cross-scale addition requires an explicit `RoundingMode` argument to resolve the rounding of the result to the receiver's scale. ### Example Usage ```java import org.decimal4j.immutable.Decimal2f; import org.decimal4j.immutable.Decimal3f; import java.math.RoundingMode; public class AddExamples { public static void main(String[] args) { Decimal2f a = Decimal2f.valueOf(4); Decimal2f b = Decimal2f.valueOf(1.5); Decimal3f c = Decimal3f.valueOf(0.125); Decimal3f d = Decimal3f.valueOf(0.5); // Same-scale addition — no rounding needed System.out.println("a+b = " + a.add(b)); // 5.50 System.out.println("c+d = " + c.add(d)); // 0.625 // Cross-scale: result adopts receiver's scale with specified rounding System.out.println("a+c = " + a.add(c, RoundingMode.HALF_UP)); // 4.13 System.out.println("c+a = " + c.add(a, RoundingMode.UNNECESSARY)); // 4.125 // Add a raw long value (interpreted as integer, no rounding needed) Decimal2f x = Decimal2f.valueOf(1.23).add(10L); // 11.23 // Add a double (converted with HALF_UP before addition) Decimal2f y = Decimal2f.valueOf(1.00).add(0.005); // 1.01 // Overflow-checked addition (throws ArithmeticException on overflow) import org.decimal4j.truncate.OverflowMode; Decimal2f safe = a.add(b, OverflowMode.CHECKED); // 5.50 — no overflow here } } ``` ``` -------------------------------- ### Run Build with Test Variant Source: https://github.com/tools4j/decimal4j/wiki/Test-Coverage Control test variants by setting the 'testVariant' system property when running the Gradle build. This influences scales, rounding modes, and random test counts. ```bash gradle clean build jacocoTestReport -DtestVariant=SMALL ``` -------------------------------- ### Multiply Decimals with Same and Different Scales Source: https://github.com/tools4j/decimal4j/wiki/Examples Demonstrates multiplication of Decimal types with identical and differing scales, including rounding modes. Use when precise multiplication is required, especially when scales vary. ```java public class Multiply { public static void main(String[] args) { Decimal2f a = Decimal2f.valueOf(4); Decimal2f b = Decimal2f.valueOf(1.5); Decimal3f c = Decimal3f.valueOf(0.125); Decimal3f d = Decimal3f.valueOf(0.5); System.out.println("MULTIPLY: values with same scale"); Decimal2f productAB = a.multiply(b); Decimal3f productCD = c.multiply(d); Decimal3f downCD = c.multiply(d, RoundingMode.DOWN); System.out.println("a*b = " + productAB); System.out.println("c*d = " + productCD); System.out.println("c*d = " + downCD); System.out.println("MULTIPLY: values with different scales"); Decimal2f productAC = a.multiplyBy(c); Decimal2f productBC = b.multiplyBy(c); Decimal2f productBD = b.multiplyBy(d); Decimal3f productCA = c.multiplyBy(a); System.out.println("a*c = " + productAC); System.out.println("b*c = " + productBC); System.out.println("b*d = " + productBD); System.out.println("c*a = " + productCA); System.out.println("MULTIPLY: exact multiplication"); Decimal exactCD = c.multiplyExact(d); Decimal6f typedCD = c.multiplyExact().by(d); Decimal5f typedAD = a.multiplyExact().by(d); System.out.println("c*d = " + exactCD); System.out.println("c*d = " + typedCD); System.out.println("a*d = " + typedAD); } } ``` -------------------------------- ### Run JMH Runner Directly Source: https://context7.com/tools4j/decimal4j/llms.txt Executes the JMH runner directly using the compiled fat-jar. This provides an alternative way to run benchmarks. ```bash java -cp build/libs/decimal4j-1.0.3-jmh.jar org.decimal4j.jmh.JmhRunner ``` -------------------------------- ### Add decimal4j Dependency to Maven Project Source: https://github.com/tools4j/decimal4j/blob/master/README.md Include this XML snippet in your Maven project's pom.xml to add the decimal4j library as a compile dependency. ```xml org.decimal4j decimal4j 1.0.3 compile ``` -------------------------------- ### Calculate Mean and Standard Deviation with MutableDecimal10f Source: https://github.com/tools4j/decimal4j/wiki/Examples Computes the mean and standard deviation of a set of Gaussian random numbers using MutableDecimal10f for efficient accumulation. Imports are not shown. ```java public class MeanStdDev { /* Random generator*/ private static final Random RND = new Random(); /* Sample count*/ private static final int N = 10000; /* Expected sample mean*/ private static final Decimal10f EXP_MEAN = Decimal10f.valueOf(0); public static void main(String[] args) { MutableDecimal10f mean = new MutableDecimal10f(); MutableDecimal10f var = new MutableDecimal10f(); for (int i = 0; i < N; i++) { double value = RND.nextGaussian(); mean.add(value); var.addSquared(EXP_MEAN.subtract(value)); } System.out.println("Mean: " + mean.divide(N)); System.out.println("Variance: " + var.divide(N)); System.out.println("StdDev: " + var.sqrt()); } } ``` -------------------------------- ### Decimal.shiftLeft() / Decimal.shiftRight() Source: https://context7.com/tools4j/decimal4j/llms.txt Efficiently multiplies or divides a Decimal value by powers of 10 using bitwise shift operations. ```APIDOC ## `Decimal.shiftLeft()` / `Decimal.shiftRight()` — Decimal Shifts `shiftLeft(n)` multiplies by 10ⁿ; `shiftRight(n)` divides by 10ⁿ. Both are more efficient than multiplying/dividing by literal powers of 10. ### Method Signatures `Decimal shiftLeft(int n)` `Decimal shiftRight(int n)` ### Example ```java import org.decimal4j.immutable.Decimal4f; Decimal4f val = Decimal4f.valueOf(1.2345); System.out.println("shift left 1: " + val.shiftLeft(1)); // 12.3450 System.out.println("shift left 2: " + val.shiftLeft(2)); // 123.4500 System.out.println("shift right 1: " + val.shiftRight(1)); // 0.1235 (HALF_UP) System.out.println("shift right 2: " + val.shiftRight(2)); // 0.0123 // Shift right is equivalent to dividing by power of 10 Decimal4f half = Decimal4f.TWO.shiftRight(1); // 0.2000 == 2 / 10 System.out.println("shiftRight(1) of 2: " + half); ``` ```