Add custom currency


Required JARs on classpath:

  • javax.money:money-api:1.0 (JSR354 money and currency api)
  • org.javamoney:moneta:1.0 (Reference implementation)
  • javax:annotation-api:1.2. (Common annotations used by reference implementation)
import org.javamoney.moneta.CurrencyUnitBuilder;
import javax.money.CurrencyUnit;
import javax.money.Monetary;
import javax.money.MonetaryAmount;
import javax.money.UnknownCurrencyException;
import javax.money.MonetaryAmountFactory;
import javax.money.MonetaryAmounts;
import java.math.BigDecimal;
 
public class CustomCurrencyExample {
    public static void main(String[] args) {
        try {
            // Attempt to create a monetary amount with non-ISO currency (e.g., bitcoin)
            MonetaryAmount customAmount = MonetaryAmounts.getAmountFactory()
                    .setCurrency("BTC")
                    .setNumber(new BigDecimal("0.1"))
                    .create();
 
            // This will throw UnknownCurrencyException if BTC is not available
            System.out.println("Currency 'BTC' available: " + Monetary.isCurrencyAvailable("BTC"));
        } catch (UnknownCurrencyException e) {
            System.out.println("UnknownCurrencyException: " + e.getMessage());
        }
 
        // Build a new currency (e.g., bitcoin) using CurrencyUnitBuilder
        CurrencyUnit bitcoin = CurrencyUnitBuilder
                .of("BTC", "BtcCurrencyProvider") // Set currency code and currency provider name
                .setDefaultFractionDigits(2) // Set default fraction digits
                .build(true); // Build new currency unit. Here 'true' means register the currency unit
 
        // Now check if BTC is available after registering
        System.out.println("Currency 'BTC' available: " + Monetary.isCurrencyAvailable("BTC"));
    }
}

Basic Programs