Currency-safe payment calculations with Java Money
Use Java Money and Moneta to combine amounts with currencies, centralize rounding policy, and persist settlements without losing their units.
Payment arithmetic needs to preserve the currency and the rounding rule. I use JSR 354 to keep those decisions in the value and its policy instead of spreading scale assumptions through services.
The examples use Java 21, money-api 1.1, and Moneta 1.4.4.
Why a decimal amount still needs a currency
Binary floating point can introduce representation error into decimal calculations. BigDecimal addresses the decimal representation but does not know whether a value is won or dollars. Adding 10,000 KRW and 10 USD as plain decimals yields 10,010, an amount with no meaningful unit.
Rounding also depends on the business operation. KRW commonly has no fractional digits, USD has two, and KWD has three. Applying setScale(2, HALF_UP) throughout a settlement service can produce inconsistent results when currencies or fee policies change.
| Representation | Arithmetic | Currency information |
|---|---|---|
double | Binary floating-point operations | Separate metadata required |
BigDecimal | Decimal operations with an explicit scale policy | Separate metadata required |
MonetaryAmount | Monetary operations with provider-specific precision | Carries a CurrencyUnit and checks incompatible currencies |
The JSR 354 contract and Moneta implementation
CurrencyUnit describes a currency code and metadata such as its usual fraction digits. MonetaryAmount couples a quantity with a currency. MonetaryRounding applies a rounding policy, and MonetaryOperator models a transformation such as a fee, tax, or discount.
flowchart TD
API["Java Money API"] --> CUR["CurrencyUnit"]
API --> AMT["MonetaryAmount"]
API --> POLICY["Rounding and operators"]
AMT --> MONEY["Moneta Money"]
AMT --> FAST["Moneta FastMoney"]
Moneta provides concrete types, including Money backed by BigDecimal and FastMoney backed by a fixed-scale long. Use the API types at module boundaries so the implementation decision stays local.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// build.gradle.kts
plugins {
java
}
dependencies {
implementation("javax.money:money-api:1.1")
implementation("org.javamoney:moneta:1.4.4")
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
}
tasks.test {
useJUnitPlatform()
}
Applying a fee and rejecting mixed currencies
The example calculates a percentage fee and rounds it at the currency’s precision before subtracting it from the gross amount. Make the rounding mode explicit. If the business requires a different method for tax and for payout, give each operation its own policy and verify how the final result reconciles.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// src/main/java/com/example/money/PaymentSettlementCalculator.java
package com.example.money;
import org.javamoney.moneta.Money;
import javax.money.CurrencyUnit;
import javax.money.Monetary;
import javax.money.MonetaryAmount;
import javax.money.MonetaryOperator;
import javax.money.MonetaryRounding;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class PaymentSettlementCalculator {
private static final BigDecimal PG_FEE_RATE = new BigDecimal("0.033"); // 3.3%
public static final MonetaryOperator PG_FEE_OPERATOR = amount -> {
MonetaryRounding defaultRounding = Monetary.getDefaultRounding();
return amount.multiply(PG_FEE_RATE).with(defaultRounding);
};
public static final MonetaryOperator TRUNCATE_TO_UNIT = amount -> {
CurrencyUnit currency = amount.getCurrency();
int fractionDigits = Math.max(currency.getDefaultFractionDigits(), 0);
BigDecimal scaled = amount.getNumber()
.numberValueExact(BigDecimal.class)
.setScale(fractionDigits, RoundingMode.DOWN);
return Money.of(scaled, currency);
};
public MonetaryAmount calculateNetSettlement(MonetaryAmount grossAmount) {
MonetaryAmount fee = grossAmount.with(PG_FEE_OPERATOR);
return grossAmount.subtract(fee).with(TRUNCATE_TO_UNIT);
}
}
The tests cover a currency mismatch and expected settlements. At 3.3%, 10,000 KRW leaves 9,670 KRW after a 330 KRW fee. At the same rate, 100.00 USD leaves 96.70 USD after a 3.30 USD fee.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// src/test/java/com/example/money/PaymentSettlementCalculatorTest.java
package com.example.money;
import org.javamoney.moneta.Money;
import org.junit.jupiter.api.Test;
import javax.money.MonetaryAmount;
import javax.money.MonetaryException;
import java.math.BigDecimal;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class PaymentSettlementCalculatorTest {
private final PaymentSettlementCalculator calculator = new PaymentSettlementCalculator();
@Test
void addingDifferentCurrenciesThrowsMonetaryException() {
MonetaryAmount krw = Money.of(10_000, "KRW");
MonetaryAmount usd = Money.of(new BigDecimal("10.00"), "USD");
assertThrows(MonetaryException.class, () -> krw.add(usd));
}
@Test
void calculatesFeesAtEachCurrencyScale() {
// KRW (0 decimals): 10,000 * 3.3% = 330. Net: KRW 9,670.
MonetaryAmount krwNet = calculator.calculateNetSettlement(Money.of(10_000, "KRW"));
assertTrue(krwNet.isEqualTo(Money.of(9_670, "KRW")));
// USD (2 decimals): 100.00 * 3.3% = 3.30. Net: USD 96.70.
MonetaryAmount usdNet = calculator.calculateNetSettlement(Money.of(new BigDecimal("100.00"), "USD"));
assertTrue(usdNet.isEqualTo(Money.of(new BigDecimal("96.70"), "USD")));
}
}
Choosing Money or FastMoney
| Concern | Moneta Money | Moneta FastMoney |
|---|---|---|
| Storage | Decimal representation | Fixed-scale integer |
| Precision | Controlled by monetary context and decimal operations | Up to five fractional digits |
| Range | Wider for typical payment values | Bounded by the signed long representation |
| Typical fit | Payments, rates, taxes, and settlement | High-frequency operations where its bounds fit |
Five fractional digits in a signed long allow values on the order of 92 trillion units. A computation can still exceed the allowed scale or range before it produces a final amount. Verify the maximum input and intermediate values before choosing the fixed-point implementation. Compare performance with the actual workload.
Keeping the currency visible outside Java
Store the numeric amount and currency code in separate columns. You can then filter by currency before applying a database aggregate. The embeddable wrapper demonstrates one way to keep those fields together in the entity.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// src/main/java/com/example/money/MoneyEmbeddable.java
package com.example.money;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import org.javamoney.moneta.Money;
import javax.money.MonetaryAmount;
import java.math.BigDecimal;
@Embeddable
public class MoneyEmbeddable {
@Column(name = "amount", precision = 19, scale = 4, nullable = false)
private BigDecimal amount;
@Column(name = "currency", length = 3, nullable = false)
private String currency;
protected MoneyEmbeddable() {}
public static MoneyEmbeddable from(MonetaryAmount money) {
MoneyEmbeddable embeddable = new MoneyEmbeddable();
embeddable.amount = money.getNumber().numberValueExact(BigDecimal.class);
embeddable.currency = money.getCurrency().getCurrencyCode();
return embeddable;
}
public MonetaryAmount toMonetaryAmount() {
return Money.of(this.amount, this.currency);
}
}
For JSON, use a stable contract such as {"amount": 10000, "currency": "KRW"}. Configure the Jackson money module or your own serializer so clients do not depend on the implementation’s internal metadata. Define how currency conversion is represented, including the applicable rate and rounding policy, if the application needs cross-currency totals.
Use a monetary comparison such as isEqualTo() for same-currency values when their numeric equality is the question. Concrete equals() implementations can differ between providers or amount classes. Before deploying settlement code, cover zero-decimal currencies, half-unit rounding, and an attempted operation across currencies.