### Implement Bitcoin Currency Provider (Java) Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-convert/moneta-convert-base/src/main/asciidoc/userguide.adoc Demonstrates how to implement a custom currency provider by extending CurrencyProviderSpi. This example shows a basic Bitcoin provider that can be registered as a CDI bean. ```java @Singleton public class BitCoinProvider implements CurrencyProviderSpi { ... } ``` -------------------------------- ### Creating Money Instances with Moneta Source: https://context7.com/javamoney/jsr354-ri/llms.txt Provides examples for creating `Money` instances, which represent monetary amounts with arbitrary precision using `BigDecimal`. Covers creation via static factory methods, zero amounts, minor units, parsing from strings, and conversion from other `MonetaryAmount` types. ```java import org.javamoney.moneta.Money; import javax.money.CurrencyUnit; import javax.money.Monetary; import javax.money.MonetaryAmount; import java.math.BigDecimal; // Create Money using static factory methods Money money1 = Money.of(100.50, "USD"); Money money2 = Money.of(new BigDecimal("1234.5678"), "EUR"); Money money3 = Money.of(500, Monetary.getCurrency("GBP")); // Create zero amount Money zero = Money.zero(Monetary.getCurrency("USD")); // Create from minor units (cents) Money fromCents = Money.ofMinor(Monetary.getCurrency("USD"), 1234); // USD 12.34 Money fromCentsCustom = Money.ofMinor(Monetary.getCurrency("USD"), 12345, 3); // USD 12.345 // Parse from string Money parsed = Money.parse("EUR 25.50"); System.out.println("Parsed: " + parsed); // EUR 25.50 // Convert between amount types MonetaryAmount anyAmount = Money.of(100, "USD"); Money converted = Money.from(anyAmount); ``` -------------------------------- ### Getting a CurrencyConversion Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-core/src/main/asciidoc/userguide.adoc Demonstrates how to obtain a CurrencyConversion operator from an ExchangeRateProvider and apply it to a MonetaryAmount. ```APIDOC ## Getting a CurrencyConversion from an ExchangeRateProvider ### Description This example shows how to get a `CurrencyConversion` operator from an `ExchangeRateProvider`. This operator is bound to a target currency (e.g., "CHF") and can be applied to a `MonetaryAmount` to convert it to the target currency. ### Method `ExchangeRateProvider.getCurrencyConversion(String targetCurrency)` `MonetaryAmount.with(MonetaryOperator operator)` ### Endpoint N/A (This is a Java API example) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java ExchangeRateProvider rateProvider = MonetaryConversions.getExchangeRateProvider(); CurrencyConversion conversion = rateProvider.getCurrencyConversion("CHF"); MonetaryAmount amountInUSD = ...; // Assume this is a MonetaryAmount in USD MonetaryAmount amountInCHF = amountInUSD.with(conversion); ``` ### Response #### Success Response (200) - **amountInCHF** (MonetaryAmount) - The original `MonetaryAmount` converted to CHF. #### Response Example ```java // If amountInUSD was 100 USD and the rate is 1 USD = 0.92 CHF, // amountInCHF would be 92 CHF. ``` ``` -------------------------------- ### Registering Custom Format Providers Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-core/src/main/asciidoc/userguide.adoc Provides an example of implementing the MonetaryAmountFormatProviderSpi to register custom currency formatters via the Java ServiceLoader. ```java public final class GeeCoinFormatProviderSpi implements MonetaryAmountFormatProviderSpi { private static final String PROVIDER_NAME = "GeeCoin"; private static final String STYLE_NAME = "GeeCoin"; private Set supportedSets = new HashSet<>(); private Set formatNames = new HashSet<>(); public GeeCoinFormatProviderSpi() { supportedSets.add(Locale.CHINA); supportedSets = Collections.unmodifiableSet(supportedSets); formatNames.add("GeeCoin"); formatNames = Collections.unmodifiableSet(formatNames); } @Override public String getProviderName() { return PROVIDER_NAME; } @Override public Collection getAmountFormats(AmountFormatQuery amountFormatQuery) { Objects.requireNonNull(amountFormatQuery, "AmountFormatContext required"); if (!amountFormatQuery.getProviderNames().isEmpty() && !amountFormatQuery.getProviderNames().contains(getProviderName())) { return Collections.emptySet(); } if (!(amountFormatQuery.getFormatName() == null || STYLE_NAME.equals(amountFormatQuery.getFormatName()))) { return Collections.emptySet(); } AmountFormatContextBuilder builder = AmountFormatContextBuilder.of(PROVIDER_NAME); if (amountFormatQuery.getLocale() != null) { builder.setLocale(amountFormatQuery.getLocale()); } builder.importContext(amountFormatQuery, false); return Collections.emptySet(); } } ``` -------------------------------- ### Implementing a Custom MonetaryAmountFormatProviderSpi in Java Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-convert/moneta-convert-base/src/main/asciidoc/userguide.adoc Provides an example implementation of MonetaryAmountFormatProviderSpi to register a custom currency format (GeeCoin) for specific locales and format names. This involves defining provider name, supported locales, and format names. ```java public final class GeeCoinFormatProviderSpi implements MonetaryAmountFormatProviderSpi { private static final String PROVIDER_NAME = "GeeCoin"; private static final String STYLE_NAME = "GeeCoin"; /** The supported locales. */ private Set supportedSets = new HashSet<>(); /** The provided formats, by name. */ private Set formatNames = new HashSet<>(); public GeeCoinFormatProviderSpi() { supportedSets.add(Locale.CHINA); supportedSets = Collections.unmodifiableSet(supportedSets); formatNames.add("GeeCoin"); formatNames = Collections.unmodifiableSet(formatNames); } /* * (non-Javadoc) * @see * javax.money.spi.MonetaryAmountFormatProviderSpi#getProviderName() */ @Override public String getProviderName() { return PROVIDER_NAME; } /* * (non-Javadoc) * @see * javax.money.spi.MonetaryAmountFormatProviderSpi#getFormat(javax.money.format.AmountFormatContext) */ @Override public Collection getAmountFormats(AmountFormatQuery amountFormatQuery) { Objects.requireNonNull(amountFormatQuery, "AmountFormatContext required"); if (!amountFormatQuery.getProviderNames().isEmpty() && !amountFormatQuery.getProviderNames().contains(getProviderName())) { return Collections.emptySet(); } if (!(amountFormatQuery.getFormatName() == null || STYLE_NAME.equals(amountFormatQuery.getFormatName()))) { return Collections.emptySet(); } AmountFormatContextBuilder builder = AmountFormatContextBuilder.of(PROVIDER_NAME); if (amountFormatQuery.getLocale() != null) { builder.setLocale(amountFormatQuery.getLocale()); } builder.importContext(amountFormatQuery, false); ``` -------------------------------- ### Access ExchangeRateProvider and ExchangeRate Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-convert/moneta-convert-base/src/main/asciidoc/userguide.adoc Demonstrates how to get an ExchangeRateProvider by its name (e.g., 'IMF') and then retrieve an ExchangeRate between two currencies. ```java ExchangeRateProvider rateProvider = MonetaryConversions.getExchangeRateProvider("IMF"); ExchangeRate chfToUsdRate = rateProvider.getExchangeRate("CHF", "USD"); ``` -------------------------------- ### Implement Custom RoundingProviderSpi Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-convert/moneta-convert-base/src/main/asciidoc/userguide.adoc Provides an example of extending the rounding system by implementing the RoundingProviderSpi interface to support custom currencies like Bitcoin (BTC). ```java public final class TestRoundingProvider implements RoundingProviderSpi { private static final MonetaryRounding ROUNDING = new MyCurrencyRounding(); private final Set roundingNames; public TestRoundingProvider() { Set names = new HashSet<>(); names.add("custom1"); this.roundingNames = Collections.unmodifiableSet(names); } @Override public MonetaryRounding getRounding(RoundingQuery roundingQuery) { CurrencyUnit cu = roundingQuery.getCurrency(); if (cu != null && "BTC".equals(cu.getCurrencyCode())) { return ROUNDING; } return null; } @Override public Set getRoundingNames() { return Collections.emptySet(); } } ``` -------------------------------- ### Accessing ExchangeRateProvider and ExchangeRate Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-core/src/main/asciidoc/userguide.adoc Demonstrates how to get an ExchangeRateProvider by name and retrieve an exchange rate between two currencies. ```APIDOC ## Access an ExchangeRateProvider and get an ExchangeRate ### Description This example shows how to obtain a specific `ExchangeRateProvider` (e.g., "IMF") from `MonetaryConversions` and then use it to get the exchange rate between two currencies (e.g., CHF to USD). ### Method `MonetaryConversions.getExchangeRateProvider(String providerName)` `ExchangeRateProvider.getExchangeRate(String baseCurrency, String targetCurrency)` ### Endpoint N/A (This is a Java API example) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java ExchangeRateProvider rateProvider = MonetaryConversions.getExchangeRateProvider("IMF"); ExchangeRate chfToUsdRate = rateProvider.getExchangeRate("CHF", "USD"); ``` ### Response #### Success Response (200) - **chfToUsdRate** (ExchangeRate) - An object representing the exchange rate from CHF to USD. #### Response Example ```java // Example of an ExchangeRate object (implementation specific) // Represents a rate of 1 CHF = 1.10 USD ``` ``` -------------------------------- ### Access and Apply Default Currency Rounding in Java Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-core/src/main/asciidoc/userguide.adoc Illustrates how to get the default rounding for a specific CurrencyUnit and apply it to a MonetaryAmount. This can be a standard arithmetic rounding or a custom one. ```java CurrencyUnit currency = ...; MonetaryRounding rounding = Monetary.getRounding(currency); MonetaryAmount amt = ...; MonetaryAmount roundedAmount = amt.with(rounding); // uses Monetary.getRounding(CurrencyUnit); ``` -------------------------------- ### GET /currencies/locale Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-core/src/main/asciidoc/userguide.adoc Retrieve a CurrencyUnit instance based on a provided Locale. ```APIDOC ## GET /currencies/locale ### Description Access a currency unit by providing a Locale representing a country. ### Method GET ### Endpoint /currencies/locale/{countryCode} ### Parameters #### Path Parameters - **countryCode** (string) - Required - The ISO country code (e.g., "USA", "SUI") ### Request Example GET /currencies/locale/USA ### Response #### Success Response (200) - **CurrencyUnit** (object) - The currency unit associated with the country. #### Response Example { "currencyCode": "USD", "country": "USA" } ``` -------------------------------- ### Creating FastMoney Instances Source: https://context7.com/javamoney/jsr354-ri/llms.txt Demonstrates how to create FastMoney instances for high-performance calculations where 5 decimal places precision is sufficient. Includes creation from values, BigDecimal, currency units, zero amounts, minor units, and parsing from strings. ```APIDOC ## Creating FastMoney Instances Use `FastMoney` for high-performance calculations when 5 decimal places precision is sufficient. ### Method N/A (Constructor/Static Factory Methods) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ## Code Examples ```java import org.javamoney.moneta.FastMoney; import javax.money.CurrencyUnit; import javax.money.Monetary; import java.math.BigDecimal; // Create FastMoney - optimized for speed (uses long internally) FastMoney fast1 = FastMoney.of(100.50, "USD"); FastMoney fast2 = FastMoney.of(new BigDecimal("1234.56789"), "EUR"); // Rounded to 5 decimals FastMoney fast3 = FastMoney.of(500, Monetary.getCurrency("GBP")); // Create zero amount FastMoney zero = FastMoney.zero(Monetary.getCurrency("USD")); // Create from minor units FastMoney fromMinor = FastMoney.ofMinor(Monetary.getCurrency("USD"), 1234); // USD 12.34 // Parse from string FastMoney parsed = FastMoney.parse("EUR 25.50000"); System.out.println("Parsed: " + parsed); // EUR 25.50000 // Performance comparison - FastMoney is ~10x faster than Money // FastMoney precision: 5 decimal places, max value: ~92 trillion System.out.println("Max value: " + FastMoney.MAX_VALUE); System.out.println("Min value: " + FastMoney.MIN_VALUE); ``` ``` -------------------------------- ### Create Money Instances with MathContext Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-convert/moneta-convert-base/src/main/asciidoc/userguide.adoc Demonstrates creating a Money instance using the MonetaryAmountFactory with a specific MathContext. This ensures consistent decimal arithmetic behavior. ```java Money money = Monetary.getAmountFactory(Money.class) .setCurrencyUnit("CHF").setNumber(200) .setContext(MonetaryContextBuilder.of().set(MathContext.DECIMAL128).build()) .create(); ``` -------------------------------- ### GET /currencies/code Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-core/src/main/asciidoc/userguide.adoc Retrieve a CurrencyUnit instance using its ISO currency code. ```APIDOC ## GET /currencies/code ### Description Access a specific currency unit using its standard ISO currency code (e.g., USD, CHF, EUR). ### Method GET ### Endpoint /currencies/{code} ### Parameters #### Path Parameters - **code** (string) - Required - The ISO currency code (e.g., "USD") ### Request Example GET /currencies/USD ### Response #### Success Response (200) - **CurrencyUnit** (object) - The currency unit instance representing the requested code. #### Response Example { "currencyCode": "USD", "numericCode": 840, "defaultFractionDigits": 2 } ``` -------------------------------- ### GET /currencies Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-convert/moneta-convert-base/src/main/asciidoc/userguide.adoc Endpoints for retrieving CurrencyUnit objects using currency codes or Locales. ```APIDOC ## GET /currencies ### Description Retrieves a CurrencyUnit instance based on a provided currency code or a Locale representing a country. ### Method GET ### Endpoint /currencies ### Parameters #### Query Parameters - **code** (string) - Optional - The ISO currency code (e.g., 'USD', 'EUR'). - **locale** (string) - Optional - The ISO country code to resolve the currency (e.g., 'USA', 'GER'). ### Request Example GET /currencies?code=USD ### Response #### Success Response (200) - **currencyCode** (string) - The ISO currency code. - **numericCode** (int) - The ISO numeric currency code. - **defaultFractionDigits** (int) - The number of fraction digits for the currency. #### Response Example { "currencyCode": "USD", "numericCode": 840, "defaultFractionDigits": 2 } ``` -------------------------------- ### Create Money instances with MathContext Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-core/src/main/asciidoc/userguide.adoc Demonstrates how to create a Money instance using a specific MathContext, either via the direct factory method or the MonetaryAmountFactory API. ```java Money money = Money.of(200, "CHF", MonetaryContextBuilder.of().set(MathContext.DECIMAL128).build()); Money moneyFactory = Monetary.getAmountFactory(Money.class) .setCurrencyUnit("CHF").setNumber(200) .setContext(MonetaryContextBuilder.of().set(MathContext.DECIMAL128).build()) .create(); ``` -------------------------------- ### Configure Moneta Library via javamoney.properties Source: https://context7.com/javamoney/jsr354-ri/llms.txt Provides a template for configuring the Moneta library, including math contexts, currency conversion provider chains, and scheduled exchange rate updates. This file should be placed in the classpath under src/main/resources. ```properties org.javamoney.moneta.Money.defaults.mathContext=DECIMAL64 org.javamoney.moneta.FastMoney.enforceScaleCompatibility=false conversion.default-chain=IDENT,ECB,IMF,ECB-HIST,ECB-HIST90 load.ECBCurrentRateProvider.type=SCHEDULED load.ECBCurrentRateProvider.urls=https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml org.javamoney.moneta.useJDKdefaultFormat=false ``` -------------------------------- ### GET /monetary/rounding Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-core/src/main/asciidoc/userguide.adoc Retrieves a MonetaryRounding instance based on a query, such as scale, rounding mode, or specific currency requirements. ```APIDOC ## GET /monetary/rounding ### Description Retrieves a rounding instance based on provided criteria such as scale and rounding mode. ### Method GET ### Endpoint /monetary/rounding ### Parameters #### Query Parameters - **scale** (int) - Optional - The target decimal scale. - **roundingMode** (string) - Optional - The rounding strategy (e.g., HALF_UP). - **currency** (string) - Optional - The ISO currency code. - **cashRounding** (boolean) - Optional - Whether to apply cash-specific rounding rules. ### Request Example { "scale": 4, "roundingMode": "HALF_UP" } ### Response #### Success Response (200) - **rounding** (MonetaryRounding) - The configured rounding instance. #### Response Example { "status": "success", "rounding": "RoundingInstance@123" } ``` -------------------------------- ### Implement MonetaryAmountFormatProviderSpi Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-convert/moneta-convert-base/src/main/asciidoc/userguide.adoc Demonstrates the implementation of a monetary format provider. It includes setting the factory and returning available locales and format names. ```java builder.setMonetaryAmountFactory(amountFormatQuery.getMonetaryAmountFactory()); return Arrays.asList(new MonetaryAmountFormat[]{new GeeCoinAmountFormat(builder.build())}); } @Override public Set getAvailableLocales() { return supportedSets; } @Override public Set getAvailableFormatNames() { return formatNames; } ``` -------------------------------- ### Get CurrencyConversion from ExchangeRateProvider Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-convert/moneta-convert-base/src/main/asciidoc/userguide.adoc Explains how to obtain a CurrencyConversion object from an ExchangeRateProvider, which is bound to a terminating currency. This conversion can then be applied to a MonetaryAmount. ```java ExchangeRateProvider rateProvider = MonetaryConversions.getExchangeRateProvider(); CurrencyConversion conversion = rateProvider.getCurrencyConversion("CHF"); MonetaryAmount amountInUSD = ...; MonetaryAmount amountInCHF = amountInUSD.with(conversion); ``` -------------------------------- ### Configuration via javamoney.properties Source: https://context7.com/javamoney/jsr354-ri/llms.txt Configure global library settings, math contexts, and exchange rate provider schedules using the javamoney.properties file. ```APIDOC ## Configuration API ### Description Configures the behavior of the Moneta library, including math precision, scale enforcement, and automatic scheduling for exchange rate providers like ECB and IMF. ### Method Configuration File (Classpath) ### Parameters - **org.javamoney.moneta.Money.defaults.mathContext** (String) - Optional - Sets the default MathContext (e.g., DECIMAL64). - **conversion.default-chain** (String) - Optional - Defines the provider chain for currency conversion. - **load.[Provider].type** (String) - Optional - Sets the scheduling type (e.g., SCHEDULED) for rate providers. ### Request Example org.javamoney.moneta.Money.defaults.mathContext=DECIMAL64 conversion.default-chain=IDENT,ECB,IMF ### Response #### Success Response - **System Configuration** - Library behavior is updated based on the provided properties. ``` -------------------------------- ### Create Money Instance via Monetary Singleton (Java) Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-core/src/main/asciidoc/userguide.adoc Illustrates creating a Money instance using the Monetary singleton's AmountFactory, similar to FastMoney, allowing explicit setting of currency and number. ```java Money m1 = Monetary.getAmountFactory(Money.class).setCurrency("USD").setNumber(200.20).create(); ``` -------------------------------- ### Define Custom MonetaryAmount Factory Methods Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-convert/moneta-convert-base/src/main/asciidoc/userguide.adoc Example of static factory methods to be implemented in custom MonetaryAmount classes for easier instantiation. ```java public static MyMoney of(String currencyCode, double number); public static MyMoney of(String currencyCode, long number); public static MyMoney of(String currencyCode, Number number); ``` -------------------------------- ### Implementing a Custom Currency Provider (e.g., Bitcoin) Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-convert/moneta-convert-base/src/main/asciidoc/userguide.adoc Shows how to implement the `CurrencyProviderSpi` interface to provide custom currency units, like Bitcoin. ```APIDOC ## Implementing a Custom Currency Provider ### Description This example demonstrates how to implement the `CurrencyProviderSpi` interface to create a custom currency provider. This allows you to define and supply non-standard currency units, such as Bitcoin, to the Javamoney system. ### Method N/A (This is an implementation of an interface) ### Endpoint N/A ### Parameters - **query** (CurrencyQuery) - Required - The query object used to filter the currencies to be returned. ### Request Example ```java public final class BitCoinProvider implements CurrencyProviderSpi { private Set bitcoinSet = new HashSet<>(); public BitCoinProvider() { bitcoinSet.add(CurrencyUnitBuilder.of("BTC", "MyCurrencyBuilder").build()); bitcoinSet = Collections.unmodifiableSet(bitcoinSet); } @Override public Set getCurrencies(CurrencyQuery query) { if (query.isEmpty() || query.getCurrencyCodes().contains("BTC") || query.getCurrencyCodes().isEmpty()) { return bitcoinSet; } return Collections.emptySet(); } } ``` ### Response #### Success Response (200) - **getCurrencies** - Returns a `Set` containing the currency units that match the provided `CurrencyQuery`. If the query is empty or matches "BTC", the Bitcoin currency unit is returned. Otherwise, an empty set is returned. #### Response Example ```java // If query is empty or contains "BTC" [CurrencyUnit[BTC]] // If query does not match [] ``` ``` -------------------------------- ### Configure Default Conversion Provider Chain Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-convert/moneta-convert-base/src/main/asciidoc/userguide.adoc Provides an example of how to override the default chain of exchange rate providers by configuring the 'conversion.default-chain' property in 'javamoney.properties'. ```properties #Currency Conversion conversion.default-chain=IDENT,ECB,IMF,ECB-HIST,ECB-HIST90 ``` -------------------------------- ### Create RoundedMoney Instances in Java Source: https://context7.com/javamoney/jsr354-ri/llms.txt Illustrates how to create RoundedMoney instances, which automatically apply rounding after each operation. This includes creating instances with default rounding, explicit MathContext, and custom MonetaryOperator for specific rounding rules, as well as zero amounts, from minor units, and parsing from strings. ```java import org.javamoney.moneta.RoundedMoney; import javax.money.CurrencyUnit; import javax.money.Monetary; import javax.money.MonetaryOperator; import javax.money.RoundingQueryBuilder; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; // Create RoundedMoney with default rounding RoundedMoney rounded1 = RoundedMoney.of(100.555, "USD"); // Rounds to USD 100.56 // Create with explicit MathContext RoundedMoney rounded2 = RoundedMoney.of( new BigDecimal("100.555"), Monetary.getCurrency("USD"), MathContext.DECIMAL32 ); // Create with custom rounding operator MonetaryOperator customRounding = Monetary.getRounding( RoundingQueryBuilder.of() .setScale(4) .set(RoundingMode.HALF_UP) .build() ); RoundedMoney rounded3 = RoundedMoney.of(100.555555, "EUR", customRounding); // Create zero and from minor units RoundedMoney zero = RoundedMoney.zero(Monetary.getCurrency("USD")); RoundedMoney fromMinor = RoundedMoney.ofMinor(Monetary.getCurrency("USD"), 1234); // Parse from string RoundedMoney parsed = RoundedMoney.parse("EUR 25.50"); System.out.println("Parsed: " + parsed); ``` -------------------------------- ### Create FastMoney Amount Instances (Java) Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-convert/moneta-convert-base/src/main/asciidoc/userguide.adoc Illustrates two ways to create instances of FastMoney, an optimized monetary amount implementation. The first method uses the Monetary singleton's amount factory, and the second uses a static factory method directly on the FastMoney class. ```java FastMoney m = Monetary.getAmountFactory(FastMoney.class).setCurrency("USD").setNumber(200.20).create(); ``` ```java FastMoney m = FastMoney.of(200.20, "USD"); ``` -------------------------------- ### Create FastMoney Instance via Monetary Singleton (Java) Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-core/src/main/asciidoc/userguide.adoc Demonstrates creating a FastMoney instance using the Monetary singleton's AmountFactory. This method allows setting currency and number values before creating the instance. ```java FastMoney m = Monetary.getAmountFactory(FastMoney.class).setCurrency("USD").setNumber(200.20).create(); ``` -------------------------------- ### Creating RoundedMoney Instances Source: https://context7.com/javamoney/jsr354-ri/llms.txt Illustrates how to create RoundedMoney instances, which apply implicit rounding after each operation. Covers creation with default rounding, explicit MathContext, and custom rounding operators. ```APIDOC ## Creating RoundedMoney Instances Use `RoundedMoney` when implicit rounding after each operation is desired. ### Method N/A (Constructor/Static Factory Methods) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ## Code Examples ```java import org.javamoney.moneta.RoundedMoney; import javax.money.CurrencyUnit; import javax.money.Monetary; import javax.money.MonetaryOperator; import javax.money.RoundingQueryBuilder; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; // Create RoundedMoney with default rounding RoundedMoney rounded1 = RoundedMoney.of(100.555, "USD"); // Rounds to USD 100.56 // Create with explicit MathContext RoundedMoney rounded2 = RoundedMoney.of( new BigDecimal("100.555"), Monetary.getCurrency("USD"), MathContext.DECIMAL32 ); // Create with custom rounding operator MonetaryOperator customRounding = Monetary.getRounding( RoundingQueryBuilder.of() .setScale(4) .set(RoundingMode.HALF_UP) .build() ); RoundedMoney rounded3 = RoundedMoney.of(100.555555, "EUR", customRounding); // Create zero and from minor units RoundedMoney zero = RoundedMoney.zero(Monetary.getCurrency("USD")); RoundedMoney fromMinor = RoundedMoney.ofMinor(Monetary.getCurrency("USD"), 1234); // Parse from string RoundedMoney parsed = RoundedMoney.parse("EUR 25.50"); System.out.println("Parsed: " + parsed); ``` ``` -------------------------------- ### Create Money Amount Instances (Java) Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-convert/moneta-convert-base/src/main/asciidoc/userguide.adoc Demonstrates how to create instances of the Money class, which uses BigDecimal internally for precise arithmetic. Similar to FastMoney, it shows creation via the Monetary singleton's amount factory and a static factory method. ```java Money m1 = Monetary.getAmountFactory(Money.class).setCurrency("USD").setNumber(200.20).create(); Money m2 = Money.of(200.20, "USD"); ``` -------------------------------- ### Programmatic Currency Unit Registration in JavaMoney Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-convert/moneta-convert-base/src/main/asciidoc/userguide.adoc Provides examples of registering and removing CurrencyUnit instances programmatically. This allows for dynamic management of currencies beyond the default JDK currencies. ```java /** * Registers a bew currency unit under its currency code. * @param currencyUnit the new currency to be registered, not null. * @return any unit instance registered previously by this instance, or null. */ public static CurrencyUnit registerCurrencyUnit(CurrencyUnit currencyUnit); /** * Registers a bew currency unit under the given Locale. * @param currencyUnit the new currency to be registered, not null. * @param locale the Locale, not null. * @return any unit instance registered previously by this instance, or null. */ public static CurrencyUnit registerCurrencyUnit(CurrencyUnit currencyUnit, Locale locale); /** * Removes a CurrencyUnit. * @param currencyCode the currency code, not null. * @return any unit instance removed, or null. */ public static CurrencyUnit removeCurrencyUnit(String currencyCode); /** * Removes a CurrencyUnit. * @param locale the Locale, not null. * @return any unit instance removed, or null. */ public static CurrencyUnit removeCurrencyUnit(Locale locale); ``` -------------------------------- ### Create FastMoney Instances in Java Source: https://context7.com/javamoney/jsr354-ri/llms.txt Demonstrates the creation of FastMoney objects, optimized for speed with internal long representation and a fixed 5 decimal place precision. It covers instantiation from various sources like doubles, BigDecimals, currency units, minor units, and strings, as well as creating zero amounts and accessing min/max values. ```java import org.javamoney.moneta.FastMoney; import javax.money.CurrencyUnit; import javax.money.Monetary; import java.math.BigDecimal; // Create FastMoney - optimized for speed (uses long internally) FastMoney fast1 = FastMoney.of(100.50, "USD"); FastMoney fast2 = FastMoney.of(new BigDecimal("1234.56789"), "EUR"); // Rounded to 5 decimals FastMoney fast3 = FastMoney.of(500, Monetary.getCurrency("GBP")); // Create zero amount FastMoney zero = FastMoney.zero(Monetary.getCurrency("USD")); // Create from minor units FastMoney fromMinor = FastMoney.ofMinor(Monetary.getCurrency("USD"), 1234); // USD 12.34 // Parse from string FastMoney parsed = FastMoney.parse("EUR 25.50000"); System.out.println("Parsed: " + parsed); // EUR 25.50000 // Performance comparison - FastMoney is ~10x faster than Money // FastMoney precision: 5 decimal places, max value: ~92 trillion System.out.println("Max value: " + FastMoney.MAX_VALUE); System.out.println("Min value: " + FastMoney.MIN_VALUE); ``` -------------------------------- ### Access Swiss Francs Cash Rounding in Java Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-core/src/main/asciidoc/userguide.adoc Provides an example of accessing a specific cash rounding for Swiss Francs (CHF) by setting the 'cashRounding' property in the RoundingQuery. This ensures amounts are rounded to the nearest 5 Rappen. ```java MonetaryRounding rounding = Monetary.getRounding( RoundingQueryBuilder.of().setCurrency(Monetary.getCurrency("CHF")).set("cashRounding", true).build() ); MonetaryAmount amt = ...; MonetaryAmount roundedAmount = amt.with(rounding); // amount rounded in CHF cash rounding ``` -------------------------------- ### Creating Custom Currency Units with Moneta Source: https://context7.com/javamoney/jsr354-ri/llms.txt Shows how to build and register custom currency units, such as cryptocurrencies or proprietary currencies, using `CurrencyUnitBuilder`. This includes setting default fraction digits, numeric codes, and associating locales, with options for immediate registration. ```java import org.javamoney.moneta.CurrencyUnitBuilder; import javax.money.CurrencyUnit; import javax.money.Monetary; import java.util.Locale; // Build a custom currency (Bitcoin) CurrencyUnit bitcoin = CurrencyUnitBuilder.of("BTC", "CryptoProvider") .setDefaultFractionDigits(8) // Bitcoin uses 8 decimal places .setNumericCode(-1) // No ISO numeric code .build(); // Build and register currency in one step CurrencyUnit customCurrency = CurrencyUnitBuilder.of("XYZ", "MyProvider") .setDefaultFractionDigits(4) .build(true); // true = register immediately // Build and register with locale association CurrencyUnit localCurrency = CurrencyUnitBuilder.of("MYC", "LocalProvider") .setDefaultFractionDigits(2) .build(true, new Locale("en", "MC")); // Associate with country locale // Now accessible via Monetary CurrencyUnit retrieved = Monetary.getCurrency("XYZ"); System.out.println("Retrieved: " + retrieved.getCurrencyCode()); ``` -------------------------------- ### Implementing a Custom Bitcoin Currency Provider in Java Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-convert/moneta-convert-base/src/main/asciidoc/userguide.adoc Shows how to implement the CurrencyProviderSpi interface to create a custom currency provider, specifically for Bitcoin. This involves defining a set of currencies and implementing the getCurrencies method. ```java public final class BitCoinProvider implements CurrencyProviderSpi { private Set bitcoinSet = new HashSet<>(); public BitCoinProvider() { bitcoinSet.add(CurrencyUnitBuilder.of("BTC", "MyCurrencyBuilder").build()); bitcoinSet = Collections.unmodifiableSet(bitcoinSet); } /** * Return a {@link CurrencyUnit} instances matching the given * {@link javax.money.CurrencyQuery}. * * @param query the {@link javax.money.CurrencyQuery} containing the parameters determining the query. not null. * @return the corresponding {@link CurrencyUnit}s matching, never null. */ @Override public Set getCurrencies(CurrencyQuery query) { // only ensure BTC is the code, or it is a default query. if (query.isEmpty() || query.getCurrencyCodes().contains("BTC") || query.getCurrencyCodes().isEmpty()) { return bitcoinSet; } return Collections.emptySet(); } } ``` -------------------------------- ### Accessing Currency Units with JSR 354 Source: https://context7.com/javamoney/jsr354-ri/llms.txt Demonstrates how to retrieve currency units using ISO codes, locales, and access all available currencies through the Monetary singleton. It also shows how to get currency properties like code, numeric code, and default fraction digits. ```java import javax.money.CurrencyUnit; import javax.money.Monetary; import java.util.Collection; import java.util.Locale; // Access currencies by ISO currency code CurrencyUnit usd = Monetary.getCurrency("USD"); CurrencyUnit eur = Monetary.getCurrency("EUR"); CurrencyUnit chf = Monetary.getCurrency("CHF"); // Access currencies by Locale (country) CurrencyUnit currencyUS = Monetary.getCurrency(Locale.US); // USD CurrencyUnit currencyGermany = Monetary.getCurrency(Locale.GERMANY); // EUR CurrencyUnit currencyJapan = Monetary.getCurrency(Locale.JAPAN); // JPY // Access all available currencies Collection allCurrencies = Monetary.getCurrencies(); System.out.println("Available currencies: " + allCurrencies.size()); // Currency properties System.out.println("Currency code: " + usd.getCurrencyCode()); // USD System.out.println("Numeric code: " + usd.getNumericCode()); // 840 System.out.println("Fraction digits: " + usd.getDefaultFractionDigits()); // 2 ``` -------------------------------- ### Accessing MonetaryAmountFormat Instances Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-core/src/main/asciidoc/userguide.adoc Demonstrates how to obtain MonetaryAmountFormat instances using different query methods: by Locale, by name, and by a complex query builder. ```APIDOC ## Accessing Amount Formats MonetaryAmountFormat instances can be accessed from the MonetaryFormats singleton. ### Method `MonetaryFormats.getAmountFormat()` ### Parameters - `locale` (Locale) - The country locale to base the format on. - `name` (String) - The unique name of the custom format. - `query` (AmountFormatQuery) - A query object to specify complex formatting parameters. ### Request Example ```java // Access by Locale MonetaryAmountFormat formatCountry = MonetaryFormats.getAmountFormat(Locale.GERMANY); // Access by Name MonetaryAmountFormat formatNamed = MonetaryFormats.getAmountFormat("MyCustomFormat"); // Access by Query MonetaryAmountFormat formatQueried = MonetaryFormats.getAmountFormat( AmountFormatQueryBuilder.of("MyCustomFormat2") .set("strict", true) .set("omitNegative", true) .set("omitNegativeSign", "N/A") .build() ); ``` ``` -------------------------------- ### Convert Between MonetaryAmount Implementations Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-convert/moneta-convert-base/src/main/asciidoc/userguide.adoc Demonstrates how to explicitly convert between different monetary amount implementations like Money and FastMoney using static from() methods. ```java MyMoney money1; Money money = Money.from(myMoney); FastMoney fastMoney = FastMoney.from(myMoney); money = Money.from(fastMoney); fastMoney = FastMoney.from(money); ``` -------------------------------- ### Create FastMoney Instance via Static Factory Method (Java) Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-core/src/main/asciidoc/userguide.adoc Shows a concise way to create FastMoney instances using the static 'of' factory method directly on the FastMoney class, simplifying instance creation. ```java FastMoney m = FastMoney.of(200.20, "USD"); ``` -------------------------------- ### Create Money Instance via Static Factory Method (Java) Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-core/src/main/asciidoc/userguide.adoc Demonstrates creating Money instances using the static 'of' factory method, providing a shorthand for common Money object creation. ```java Money m2 = Money.of(200.20, "USD"); ``` -------------------------------- ### Configure Money Instance with MathContext (Java) Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-convert/moneta-convert-base/src/main/asciidoc/userguide.adoc Explains how to configure Money instances with a specific MathContext for controlling arithmetic precision and rounding, which is based on java.math.BigDecimal's capabilities. ```java // Creating instances of +Money+ configuring the +MathContext+ to be used. // Example usage would involve passing a MonetaryContext containing the MathContext. ``` -------------------------------- ### Register Custom CurrencyUnit Programmatically (Java) Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-convert/moneta-convert-base/src/main/asciidoc/userguide.adoc Shows how to create and register custom CurrencyUnit instances using CurrencyUnitBuilder. This includes registering a currency with default settings and for a specific locale. It also demonstrates a shorthand for registering during the build process. ```java CurrencyUnit unit = CurrencyUnitBuilder.of("FLS22", "MyCurrencyProvider") .setDefaultFractionDigits(3) .build(); // registering it Monetary.registerCurrency(unit); Monetary.registerCurrency(unit, Locale.MyCOUNTRY); ``` ```java CurrencyUnitBuilder.of("FLS22", "MyCurrencyProvider") .setDefaultFractionDigits(3) .build(true /* register */); ``` -------------------------------- ### Creating Locales for Currency Access Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-convert/moneta-convert-base/src/main/asciidoc/userguide.adoc Shows how to instantiate a Locale object using an ISO country code, which is a prerequisite for locale-based currency lookups. ```java String isoCountry = "USA"; Locale country = new Locale("", isoCountry); ``` -------------------------------- ### Accessing All Currencies Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-convert/moneta-convert-base/src/main/asciidoc/userguide.adoc Demonstrates how to retrieve a collection of all available currency units. ```APIDOC ## Accessing All Currencies ### Description Retrieves a collection of all available currency units managed by the system. ### Method N/A (This is a static method call) ### Endpoint N/A ### Parameters None ### Request Example ```java Collection allCurrencies = Monetary.getCurrencies(); ``` ### Response #### Success Response (200) - **allCurrencies** (Collection) - A collection containing all registered CurrencyUnit instances. #### Response Example ```java // Example output (actual currencies depend on configuration and JDK) [CurrencyUnit[ISO:USD], CurrencyUnit[ISO:EUR], CurrencyUnit[ISO:JPY]] ``` ``` -------------------------------- ### Access and Apply Arithmetic Rounding in Java Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-core/src/main/asciidoc/userguide.adoc Demonstrates how to obtain a specific arithmetic rounding instance using RoundingQueryBuilder and apply it to a MonetaryAmount. It requires the Monetary API and RoundingMode. ```java MonetaryRounding rounding = Monetary.getRounding( RoundingQueryBuilder.of().setScale(4).set(RoundingMode.HALF_UP).build()); MonetaryAmount amt = ...; MonetaryAmount roundedAmount = amt.with(rounding); ``` -------------------------------- ### Perform Currency Conversion Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-core/src/main/asciidoc/userguide.adoc Demonstrates how to obtain a CurrencyConversion instance from a provider and apply it to a MonetaryAmount to perform a currency conversion. ```java ExchangeRateProvider rateProvider = MonetaryConversions.getExchangeRateProvider(); CurrencyConversion conversion = rateProvider.getCurrencyConversion("CHF"); MonetaryAmount amountInUSD = ...; MonetaryAmount amountInCHF = amountInUSD.with(conversion); ``` -------------------------------- ### ServiceLoader Configuration for Custom Currency Provider Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-convert/moneta-convert-base/src/main/asciidoc/userguide.adoc Illustrates the necessary configuration file for enabling a custom currency provider to be loaded by Java's ServiceLoader mechanism. This file should be placed in META-INF/services. ```listing javax.money.spi.CurrencyProviderSpi ``` -------------------------------- ### Access and Apply Arithmetic Rounding Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-convert/moneta-convert-base/src/main/asciidoc/userguide.adoc Demonstrates how to create a custom rounding instance using RoundingQueryBuilder with a specific scale and rounding mode, then applying it to a MonetaryAmount. ```java MonetaryRounding rounding = Monetary.getRounding(RoundingQueryBuilder.of().setScale(4).set(RoundingMode.HALF_UP).build()); MonetaryAmount amt = ...; MonetaryAmount roundedAmount = amt.with(rounding); ``` -------------------------------- ### Performing Currency Conversion Source: https://context7.com/javamoney/jsr354-ri/llms.txt Illustrates how to retrieve exchange rate providers and perform currency conversions. It covers using specific providers like ECB or IMF and chaining them for fallback support. ```java import org.javamoney.moneta.Money; import javax.money.MonetaryAmount; import javax.money.convert.CurrencyConversion; import javax.money.convert.ExchangeRateProvider; import javax.money.convert.MonetaryConversions; // Get specific providers ExchangeRateProvider ecbProvider = MonetaryConversions.getExchangeRateProvider("ECB"); // Create currency conversion CurrencyConversion toUsd = ecbProvider.getCurrencyConversion("USD"); // Convert amounts MonetaryAmount euros = Money.of(100, "EUR"); MonetaryAmount dollars = euros.with(toUsd); ``` -------------------------------- ### Implement RoundingProviderSpi for Custom Rounding in Java Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-core/src/main/asciidoc/userguide.adoc Demonstrates how to implement the RoundingProviderSpi interface to register a custom rounding for a specific currency, such as Bitcoin (BTC). This involves defining a MonetaryRounding and making it available via ServiceLoader. ```java public final class TestRoundingProvider implements RoundingProviderSpi { private static final MonetaryRounding ROUNDING = new MyCurrencyRounding(); private final Set roundingNames; public TestRoundingProvider() { Set names = new HashSet<>(); names.add("custom1"); this.roundingNames = Collections.unmodifiableSet(names); } @Override public MonetaryRounding getRounding(RoundingQuery roundingQuery) { CurrencyUnit cu = roundingQuery.getCurrency(); if (cu != null && "BTC".equals(cu.getCurrencyCode())) { return ROUNDING; } return null; } @Override public Set getRoundingNames() { return Collections.emptySet(); } } ``` -------------------------------- ### Perform Monetary Arithmetic Operations Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-convert/moneta-convert-base/src/main/asciidoc/userguide.adoc Demonstrates basic arithmetic operations including addition, subtraction, multiplication, division, and rounding using the Moneta implementation. ```java M money1 = money1.add(M.of(EURO, 1234567.3444)); money1 = money1.subtract(M.of(EURO, 232323)); money1 = money1.multiply(3.4); money1 = money1.divide(5.456); money1 = money1.with(Monetary.getRounding()); ``` -------------------------------- ### Configuring the Default Exchange Rate Provider Chain Source: https://github.com/javamoney/jsr354-ri/blob/master/moneta-core/src/main/asciidoc/userguide.adoc Explains how to override the default chain of exchange rate providers using the `javamoney.properties` file. ```APIDOC ## Configuring the default conversion provider chain ### Description The default chain of exchange rate providers used by `MonetaryConversions.getExchangeRateProvider()` can be configured. By default, it is set to `IDENT,ECB,IMF,ECB-HIST,ECB-HIST90`. You can override this by setting the `conversion.default-chain` property in your `javamoney.properties` file. ### Method Configuration via `javamoney.properties` file. ### Endpoint N/A (Configuration file setting) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```properties #Currency Conversion conversion.default-chain=IDENT,IMF,ECB ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Add Moneta Dependency (Gradle) Source: https://github.com/javamoney/jsr354-ri/blob/master/README.md This snippet demonstrates how to add the Moneta library as a dependency in a Gradle project. It specifies the group, name, version, and extension type. ```groovy compile group: 'org.javamoney', name: 'moneta', version: '1.4.5', ext: 'pom' ```