public interface MonetaryAmountFormat extends MonetaryQuery<java.lang.String>
Formats instances of MonetaryAmount
to a String
or an Appendable
.
To obtain a MonetaryAmountFormat
for a specific locale, including the default
locale, call MonetaryFormats.getAmountFormat(java.util.Locale)
. In general, do prefer
accessing MonetaryAmountFormat
instances from the MonetaryFormats
singleton,
instead of instantiating implementations directly, since the MonetaryFormats
factory
method may return different subclasses or may implement contextual behaviour (in a EE context).
If you need to customize the format object, do something like this:
MonetaryAmountFormat f = MonetaryFormats.getInstance(loc); f.setStyle(f.getStyle().toBuilder().setPattern("###.##;(###.##)").create());
A MonetaryAmountFormat
comprises a pattern and a set of symbols.
Since instances of MonetaryAmountFormat
are modelled as immutable instances they may be
shared among threads. As shown above, changes must be done by creating corresponding builder
instances. The builder acquired can be used to change the format's pattern (calling
setPattern(String)
), and/or AmountFormatSymbols
(calling
setSymbols(AmountFormatSymbols)
). The pattern and symbols provided are defined by
the MonetaryAmountFormatProviderSpi
implementations registered. In Java SE typically
implementations will delegate number formatting to java.text.DecialFormat
, which reads
data from localized ResourceBundle
s.
MonetaryAmountFormat
patterns have the same syntax as
java.text.DecimalFormat
: Pattern: PositivePattern PositivePattern ; NegativePattern PositivePattern: Prefixopt Number Suffixopt NegativePattern: Prefixopt Number Suffixopt Prefix: any Unicode characters except \uFFFE, \uFFFF, and special characters Suffix: any Unicode characters except \uFFFE, \uFFFF, and special characters Number: Integer Exponentopt Integer . Fraction Exponentopt Integer: MinimumInteger # # Integer # , Integer MinimumInteger: 0 0 MinimumInteger 0 , MinimumInteger Fraction: MinimumFractionopt OptionalFractionopt MinimumFraction: 0 MinimumFractionopt OptionalFraction: # OptionalFractionopt Exponent: E MinimumExponent MinimumExponent: 0 MinimumExponentopt
A MonetaryAmountFormat
pattern contains a positive and negative subpattern, for
example, "#,##0.00;(#,##0.00)"
. Each subpattern has a prefix, numeric part, and
suffix. The negative subpattern is optional; if absent, then the positive subpattern prefixed
with the localized minus sign ('-'
in most locales) is used as the negative
subpattern. That is, "0.00"
alone is equivalent to "0.00;-0.00"
. If
there is an explicit negative subpattern, it serves only to specify the negative prefix and
suffix; the number of digits, minimal digits, and other characteristics are all the same as the
positive pattern. That means that "#,##0.0#;(#)"
produces precisely the same
behavior as "#,##0.0#;(#,##0.0#)"
.
The prefixes, suffixes, and various symbols used for infinity, digits, thousands separators,
decimal separators, etc. may be set to arbitrary values, and they will appear properly during
formatting. However, care must be taken that the symbols and strings do not conflict, or parsing
will be unreliable. For example, either the positive and negative prefixes or the suffixes must
be distinct for DecimalFormat.parse()
to be able to distinguish positive from
negative values. (If they are identical, then MonetaryAmountFormat
will behave as if
no negative subpattern was specified.) Another example is that the decimal separator and
thousands separator should be distinct characters, or parsing will be impossible.
The grouping separator is commonly used for thousands, but in some countries it separates
ten-thousands. Where as java.text.DecimalFormat
relies on a constant grouping size of
digits between the grouping characters, such as 3 for 100,000,000 or 4 for 1,0000,0000, instances
of this interface support also grouping with different grouping sizes, e.g. [2,3] will result in
1,000,000,00, or [1,1,2,3] will result in 10,000,00,0,0. Hereby the first elements in the
grouping array will define the group sizes of the first group, starting from the decimal point.
The last element in the array will be used as default grouping size, used for all
subsequent groupings. Passing an empty array [] will disable grouping.
A similar mechanism also allows to define different grouping characters. E.g. ['\'', '.'] with grouping sizes [3] will result in 100.000'000.
Many characters in a pattern are taken literally; they are matched during parsing and output unchanged during formatting. Special characters, on the other hand, stand for other characters, strings, or classes of characters. They must be quoted, unless noted otherwise, if they are to appear in the prefix or suffix as literals.
The characters listed here are used in non-localized patterns. Localized patterns use the
corresponding characters taken from this formatter's DecimalFormatSymbols
object
instead, and these characters lose their special status. Two exceptions are the currency sign and
quote, which are not localized.
Symbol Location Localized? Meaning 0
Number Yes Digit #
Number Yes Digit, zero shows as absent .
Number Yes Decimal separator or monetary decimal separator -
Number Yes Minus sign ,
Number Yes Grouping separator E
Number Yes Separates mantissa and exponent in scientific notation. Need not be quoted in prefix or suffix. ;
Subpattern boundary Yes Separates positive and negative subpatterns ¤
(\u00A4
)Prefix or suffix No Currency sign, replaced by currency symbol. Differemt to SE, doubling of the currency symbol, will have no effect, since the currency formatting is controlled by the CurrencyStyle
set on the format'sAmountStyle
.'
Prefix or suffix No Used to quote special characters in a prefix or suffix, for example, "'#'#"
formats 123 to"#123"
. To create a single quote itself, use two in a row:"# o''clock"
.
Numbers in scientific notation are expressed as the product of a mantissa and a power of ten, for
example, 1234 can be expressed as 1.234 x 10^3. The mantissa is often in the range 1.0 <= x <
10.0, but it need not be. DecimalFormat
can be instructed to format and parse
scientific notation only via a pattern; there is currently no factory method that
creates a scientific notation format. In a pattern, the exponent character immediately followed
by one or more digit characters indicates scientific notation. Example: "0.###E0"
formats the number 1234 as "1.234E3"
.
"0.###E0 m/s"
.
"##0.#####E0"
. Using this pattern, the number 12345 formats to
"12.345E3"
, and 123456 formats to "123.456E3"
.
"00.###E0"
yields "12.3E-4"
.
"##0.##E0"
is "12.3E3"
. To show all
digits, set the significant digits count to zero. The number of significant digits does not
affect parsing.
MonetaryAmountFormat
provides arbitrary rounding (modeled as
MonetaryOperator
) to be applied on display (before printing the formatted amount) and on
parse (converting a parsed amount before returning the parsed result).
DecimalFormat
uses the ten consecutive characters starting with the
localized zero digit defined in the AmountFormatSymbols
object as digits. For
parsing, these digits as well as all Unicode decimal digits, as defined by
Character.digit
, are recognized.
NaN
is formatted as a string, which typically has a single character
\uFFFD
. This is the only value for which the prefixes and suffixes are not used.
Infinity is formatted as a string, which typically has a single character \u221E
, with the positive or negative prefixes and suffixes applied. The infinity string is determined
by the AmountFormatSymbols
object.
Negative zero ("-0"
) should always parse to
0
Instances of this class are not required to be thread-safe. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.
// Print out a number using the localized number, currency, // for each locale Locale[] locales = MonetaryFormats.getAvailableLocales(); MonetaryAmount amount = ...; MonetaryAmountFormat form; System.out.println("FORMAT"); for (int i = 0; i < locales.length; ++i) { if (locales[i].getCountry().length() == 0) { continue; // Skip language-only locales } System.out.print(locales[i].getDisplayName()); form = MonetaryFormats.getInstance(locales[i]); System.out.print(": " + form.getStyle().getPattern()); String myAmount = form.format(amount); System.out.print(" -> " + myAmount); try { System.out.println(" -> " + form.parse(form.format(myAmount))); } catch (ParseException e) {} } }
Modifier and Type | Method and Description |
---|---|
java.lang.String |
format(MonetaryAmount amount)
Formats the given
MonetaryAmount to a String. |
AmountStyle |
getAmountStyle()
The
AmountStyle to be applied when a MonetaryAmount is formatted. |
CurrencyUnit |
getDefaultCurrency()
The
CurrencyUnit to be applied when a MonetaryAmount is parsed and no
CurrencyUnit is provided within the pattern. |
MonetaryContext |
getMonetaryContext()
The
MonetaryContext to be applied when a MonetaryAmount is parsed. |
MonetaryAmount |
parse(java.lang.CharSequence text)
Fully parses the text into an instance of
MonetaryAmount . |
void |
print(java.lang.Appendable appendable,
MonetaryAmount amount)
Formats the given
MonetaryAmount to a Appendable . |
void |
setAmountStyle(AmountStyle style)
Set the
AmountStyle to be used. |
void |
setDefaultCurrency(CurrencyUnit currency)
Set the
CurrencyUnit to be used. |
void |
setMonetaryContext(MonetaryContext context)
Set the
MonetaryContext to be used. |
queryFrom
java.lang.String format(MonetaryAmount amount)
MonetaryAmount
to a String.amount
- the amount to format, not null
java.lang.UnsupportedOperationException
- if the formatter is unable to printAmountStyle getAmountStyle()
AmountStyle
to be applied when a MonetaryAmount
is formatted.AmountStyle
used, never null
.CurrencyUnit getDefaultCurrency()
CurrencyUnit
to be applied when a MonetaryAmount
is parsed and no
CurrencyUnit
is provided within the pattern.CurrencyUnit
used, or null
, if no such default
CurrencyUnit
is set.MonetaryContext getMonetaryContext()
MonetaryContext
to be applied when a MonetaryAmount
is parsed.MonetaryContext
used, or null
, when the defaults should be used.MonetaryAmount.getMonetaryContext()
MonetaryAmount parse(java.lang.CharSequence text) throws MonetaryParseException
MonetaryAmount
.
The parse must complete normally and parse the entire text. If the parse completes without reading the entire length of the text, an exception is thrown. If any other problem occurs during parsing, an exception is thrown.
This method uses a mainly delegates to contained AmountStyle
. Additionally when no
currency is on the input stream, the value of getDefaultCurrency()
is used instead
of.
Additionally the effective implementation type returned can be determined by the
MonetaryContext
applied to the MonetaryAmountFormat
. This formatter will call
MonetaryAmounts.getDefaultAmountType()
and will use the result returned
to access a corresponding MonetaryAmountFactory
to create the instance
returned.
text
- the text to parse, not nullnull
java.lang.UnsupportedOperationException
- if the formatter is unable to parseMonetaryParseException
- if there is a problem while parsingvoid print(java.lang.Appendable appendable, MonetaryAmount amount) throws java.io.IOException
MonetaryAmount
to a Appendable
.
Example implementations of Appendable
are StringBuilder
, StringBuffer
or Writer
. Note that StringBuilder
and StringBuffer
never throw an
IOException
.
appendable
- the appendable to add to, not nullamount
- the amount to print, not nulljava.lang.UnsupportedOperationException
- if the formatter is unable to printjava.io.IOException
- if an IO error occurs, thrown by the appendable
MonetaryParseException
- if there is a problem while parsingvoid setAmountStyle(AmountStyle style)
AmountStyle
to be used.style
- the style, not null.void setDefaultCurrency(CurrencyUnit currency)
CurrencyUnit
to be used.currency
- the currency. When set to null, parsing of an amount without any parseable
currency information will fail, creating a MonetaryParseException
.void setMonetaryContext(MonetaryContext context)
MonetaryContext
to be used.context
- the context, or null
for using the default MonetaryContext
as
returned by MonetaryAmountFactory.getDefaultMonetaryContext()
returned
from the MonetaryAmountFactory
as returned by
MonetaryAmounts.getAmountFactory()
.