Class BtcFormat
- java.lang.Object
-
- java.text.Format
-
- org.bitcoinj.utils.BtcFormat
-
- All Implemented Interfaces:
java.io.Serializable
,java.lang.Cloneable
- Direct Known Subclasses:
BtcAutoFormat
,BtcFixedFormat
public abstract class BtcFormat extends java.text.Format
Instances of this class format and parse locale-specific numerical representations of Bitcoin monetary values.
A primary goal of this class is to minimize the danger of human-misreading of monetary values due to mis-counting the number of zeros (or, more generally, of decimal places) in the number that represents a Bitcoin monetary value. Some of the features offered for doing this are:
- automatic adjustment of denominational units in which a value is represented so as to lessen the number of adjacent zeros,
- use of locale-specific decimal-separators to group digits in the integer portion of formatted numbers,
- fine control over the number and grouping of fractional decimal places, and
- access to character information that allows for vertical alignment of tabular columns of formatted values.
Basic Usage
Basic usage is very simple:
- Construct a new formatter object using one of the factory methods.
- Format a value by passing it as an argument to the
Format.format(Object)
method. - Parse a value by passing a
String
-type representation of it to theparse(String)
method.
For example, depending on your locale, values might be formatted and parsed as follows:
BtcFormat f = BtcFormat.getInstance(); String c = f.format(Coin.COIN); // "BTC 1.00" String k = f.format(Coin.COIN.multiply(1000)); // "BTC 1,000.00" String m = f.format(Coin.COIN.divide(1000)); // "mBTC 1.00" Coin all = f.parseObject("M฿ 21"); // All the money in the world
Auto-Denomination versus Fixed-Denomination
There are two provided concrete classes, one that automatically denominates values to be formatted,
BtcAutoFormat
, and another that formats any value in units of a fixed, specified denomination,BtcFixedFormat
.Automatic Denomination
Automatic denomination means that the formatter adjusts the denominational units in which a formatted number is expressed based on the monetary value that number represents. An auto-denominating formatter is defined by its style, specified by one of the enumerated values of
BtcAutoFormat.Style
. There are two styles constants:BtcAutoFormat.Style.CODE
(the default), andBtcAutoFormat.Style.SYMBOL
. The difference is that theCODE
style uses an internationally-distinct currency code, such as"BTC"
, to indicate the units of denomination, while theSYMBOL
style uses a possibly-ambiguous currency symbol such as"฿"
.The denomination used when formatting will be either bitcoin, millicoin or microcoin, depending on the value being represented, chosen so as to minimize the number of consecutive zeros displayed without losing precision. For example, depending on the locale, a value of one bitcoin might be formatted as
฿1.00
where a value exceeding that by one satoshi would beµ฿1,000,000.01
Fixed Denomination
Fixed denomination means that the same denomination of units is used for every value that is formatted or parsed by a given formatter instance. A fixed-denomination formatter is defined by its scale, which is the number of places one must shift the decimal point in increasing precision to convert the representation of a given quantity of bitcoins into a representation of the same value denominated in the formatter's units. For example, a scale value of
3
specifies a denomination of millibitcoins, because to represent1.0000 BTC
, or one bitcoin, in millibitcoins, one shifts the decimal point three places, that is, to1000.0 mBTC
.Construction
There are two ways to obtain an instance of this class:
- Use one of the factory methods; or
- Use a
BtcFormat.Builder
object.
The factory methods are appropriate for basic use where the default configuration is either used or modified. The
BtcFormat.Builder
class provides more control over the configuration, and gives access to some features not available through the factory methods, such as using custom formatting patterns and currency symbols.Factory Methods
Although formatting and parsing is performed by one of the concrete subclasses, you can obtain formatters using the various static factory methods of this abstract base class
BtcFormat
. There are a variety of overloaded methods that allow you to obtain a formatter that behaves according to your needs.The primary distinction is between automatic- and fixed-denomination formatters. By default, the
getInstance()
method with no arguments returns a new, automatic-denominatingBtcAutoFormat
instance for your default locale that will display exactly two fractional decimal places and a currency code. For example, if you happen to be in the USA:BtcFormat f = BtcFormat.getInstance(); String s = f.format(Coin.COIN); // "BTC 1.00"
The first argument to
getInstance()
can determine whether you get an auto- or fixed-denominating formatter. If the type of the first argument is anint
, then the value of thatint
will be interpreted as the decimal-place scale of theBtcFixedFormat
instance that is returned, and thus will determine its denomination. For example, if you want to format values in units of microbitcoins:BtcFormat m = BtcFormat.getInstance(6); String s = m.format(Coin.COIN); // "1,000,000.00"
This class provides several constants bound to common scale values:
BtcFormat milliFormat = BtcFormat.getInstance(MILLICOIN_SCALE);
Alternatively, if the type of the first argument to
getInstance()
is one of the enumerated values of theBtcAutoFormat.Style
type, eitherBtcAutoFormat.Style.CODE
orBtcAutoFormat.Style.SYMBOL
, then you will get aBtcAutoFormat
instance that uses either a currency code or symbol, respectively, to indicate the results of its auto-denomination.BtcFormat s = BtcFormat.getInstance(SYMBOL); Coin value = Coin.parseCoin("0.1234"); String mil = s.format(value); // "₥฿123.40" String mic = s.format(value.divide(1000)); // "µ฿123.40"
An alternative way to specify whether you want an auto- or fixed-denomination formatter is to use one of the factory methods that is named to indicate that characteristics of the new instance returned. For fixed-denomination formatters, these methods are
getCoinInstance()
,getMilliInstance()
, andgetMicroInstance()
. These three methods are equivalent to invokinggetInstance()
with a first argument of0
,3
and6
, respectively. For auto-denominating formatters the relevant factory methods aregetCodeInstance()
andgetSymbolInstance()
, which are equivalent togetInstance(Style.CODE)
, andgetInstance(Style.SYMBOL)
.Regardless of how you specify whether your new formatter is to be of automatic- or fixed-denomination, the next (and possibly first) parameter to each of the factory methods is an optional
Locale
value.For example, here we construct four instances for the same locale that each format differently the same one-bitcoin value:
// Next line returns "1,00 BTC" BtcFormat.getInstance(Locale.GERMANY).format(Coin.COIN); // Next line returns "1,00 ฿" BtcFormat.getInstance(SYMBOL, Locale.GERMANY).format(Coin.COIN); // Next line returns "1.000,00" BtcFormat.getMilliInstance(Locale.GERMANY).format(Coin.COIN); // Next line returns "10.000,00" BtcFormat.getInstance(4, Locale.GERMANY).format(Coin.COIN);
Omitting such a
Locale
parameter will give you a formatter for your default locale.The final (and possibly only) arguments to the factory methods serve to set the default number of fractional decimal places that will be displayed when formatting monetary values. In the case of an auto-denominating formatter, this can be a single
int
value, which will determine the number of fractional decimal places to be used in all cases, except where either (1) doing so would provide a place for fractional satoshis, or (2) that default value is overridden when invoking theformat()
method as described below.In the case of a fixed-denomination formatter, you can pass any number of
int
values. The first will determine the minimum number of fractional decimal places, and each followingint
value specifies the size of an optional group of decimal-places to be displayed only if useful for expressing precision. As with auto-denominating formatters, numbers will never be formatted with a decimal place that represents a fractional quantity of satoshis, and these defaults can be overridden by arguments to theformat()
method. See below for examples.The
BtcFormat.Builder
ClassA new
BtcFormat.Builder
instance is returned by thebuilder()
method. Such an object has methods that set the configuration parameters of aBtcFormat
object. ItsBtcFormat.Builder.build()
method constructs and returns aBtcFormat
instance configured according to those settings.In addition to setter-methods that correspond to the factory-method parameters explained above, a
BtcFormat.Builder
also allows you to specify custom formatting and parsing patterns and currency symbols and codes. For example, rather than using the default currency symbol, which has the same unicode character point as the national currency symbol of Thailand, some people prefer to use a capital letter "B" with a vertical overstrike.
TheBtcFormat.Builder builder = BtcFormat.builder(); builder.style(SYMBOL); builder.symbol("B\u20e6"); // unicode char "double vertical stroke overlay" BtcFormat f = builder.build(); String out = f.format(COIN); // "B⃦1.00" depending on locale
BtcFormat.Builder
methods are chainable. So, for example, if you are deferential to ISO 4217, you might construct a formatter in a single line this way:BtcFormat f = BtcFormat.builder().style(CODE).code("XBT").build(); String out = f.format(COIN); // "XBT 1.00"
See the documentation of the
BtcFormat.Builder
class for details.Formatting
You format a Bitcoin monetary value by passing it to the
Format.format(Object)
method. This argument can be either aCoin
-type object or a numerical object such asLong
orBigDecimal
. Integer-based types such asBigInteger
are interpreted as representing a number of satoshis, while aBigDecimal
is interpreted as representing a number of bitcoins. A value having a fractional amount of satoshis is rounded to the nearest whole satoshi at least, and possibly to a greater unit depending on the number of fractional decimal-places displayed. Theformat()
method will not accept an argument whose type isString
,Float
norDouble
.Subsequent to the monetary value to be formatted, the
Format.format(Object)
method also accepts as arguments optionalint
values that specify the number of decimal places to use to represent the fractional portion of the number. This overrides the default, and enables a single formatter instance to be reused, formatting different values that require different numbers of fractional decimal places. These parameters have the same meaning as those that set the default values in the factory methods as described above. Namely, a singleint
value determines the minimum number of fractional decimal places that will be used in all cases, to a precision limit of satoshis. Instances ofBtcFixedFormat
also accept a variable-length sequence of additionalint
values, each of which specifies the size of a group of fractional decimal-places to be used in addition to all preceding places, only if useful to express precision, and only to a maximum precision of satoshis. For example:BtcFormat f = BtcFormat.getCoinInstance(); Coin value = COIN.add(Coin.valueOf(5)); // 100000005 satoshis f.format(value, 2); // "1.00" f.format(value, 3); // "1.000" f.format(value, 2, 3); // "1.00" three more zeros doesn't help f.format(value, 2, 3, 3); // "1.00000005" f.format(value, 2, 3, 4); // "1.00000005" fractions of satoshis have no place f.format(value, 2, 3, 2); // "1.0000001" rounds to nearest usable place
Note that if using all the fractional decimal places in a specified group would give a place to fractions of satoshis, then the size of that group will be reduced to a maximum precision of satoshis. Either all or none of the allowed decimal places of that group will still be applied as doing so is useful for expressing the precision of the value being formatted.
Several convenient constants of repeating group-size sequences are provided:
BtcFixedFormat.REPEATING_PLACES
,BtcFixedFormat.REPEATING_DOUBLETS
andBtcFixedFormat.REPEATING_TRIPLETS
. These signify repeating groups of one, two and three decimals places, respectively. For example, to display only as many fractional places as useful in order to prevent hanging zeros on the least-significant end of formatted numbers:format(value, 0, REPEATING_PLACES);
When using an automatically-denominating formatter, you might want to know what denomination was chosen. You can get the currency-units indicator, as well as any other field in the formatted output, by using a
FieldPosition
instance constructed using an appropriate constant from theNumberFormat.Field
class:BtcFormat de = BtcFormat.getInstance(Locale.GERMANY); FieldPosition currField = new FieldPosition(NumberFormat.Field.CURRENCY); // next line formats the value as "987.654.321,23 µBTC" String output = de.format(valueOf(98765432123L), new StringBuffer(), currField); // next line sets variable currencyCode to "µBTC" String currencyCode = output.substring(currField.getBeginIndex(), currField.getEndIndex()));
When using a fixed-denomination formatter whose scale can be expressed as a standard "metric" prefix, you can invoke the
code()
andsymbol()
methods to obtain aString
whose value is the appropriate currency code or symbol, respectively, for that formatter.BtcFixedFormat kilo = (BtcFixedFormat)BtcFormat(-3); // scale -3 for kilocoins Coin value = Coin.parseCoin("1230"); // variable coded will be set to "kBTC 1.23" String coded = kilo.code() + " " + kilo.format(value); // variable symbolic will be set to "k฿1.23" String symbolic = kilo.symbol() + kilo.format(value); BtcFormat(4).code(); // unnamed denomination has no code; raises exception
Formatting for Tabular Columns
When displaying tables of monetary values, you can lessen the risk of human misreading-error by vertically aligning the decimal separator of those values. This example demonstrates one way to do that:
Assuming you are using a monospaced font, and depending on your locale, the foregoing will print the following:// The elements of this array are the values we will format: Coin[] rows = {MAX_MONEY, MAX_MONEY.subtract(SATOSHI), Coin.parseCoin("1234"), COIN, COIN.divide(1000), valueOf(10000), valueOf(1000), valueOf(100), SATOSHI}; BtcFormat f = BtcFormat.getCoinInstance(2, REPEATING_PLACES); FieldPosition fp = new FieldPosition(DECIMAL_SEPARATOR); // see java.text.NumberFormat.Field String[] output = new String[rows.length]; int[] indexes = new int[rows.length]; int maxIndex = 0; for (int i = 0; i < rows.length; i++) { output[i] = f.format(rows[i], new StringBuffer(), fp).toString(); indexes[i] = fp.getBeginIndex(); if (indexes[i] > maxIndex) maxIndex = indexes[i]; } for (int i = 0; i < output.length; i++) { System.out.println(repeat(" ", (maxIndex - indexes[i])) + output[i]); }
21,000,000.00 20,999,999.99999999 1,234.00 1.00 0.001 0.0001 0.00001 0.000001 0.00000001
If you need to vertically-align columns printed in a proportional font, then see the documentation for the
NumberFormat
class for an explanation of how to do that.Parsing
The
parse(String)
method accepts aString
argument, and returns aCoin
-type value. The difference in parsing behavior between instances ofBtcFixedFormat
andBtcAutoFormat
is analogous to the difference in formatting behavior between instances of those classes. Instances ofBtcAutoFormat
recognize currency codes and symbols in theString
being parsed, and interpret them as indicators of the units in which the number being parsed is denominated. On the other hand, instances ofBtcFixedFormat
by default recognize no codes nor symbols, but rather interpret every number as being denominated in the units that were specified when constructing the instance doing the parsing. This default behavior ofBtcFixedFormat
can be overridden by setting a parsing pattern that includes a currency sign using thepattern()
method.The
parse(String)
method ofBtcAutoFormat
(and ofBtcAutoFormat
configured with applicable non-default pattern) will recognize a variety of currency symbols and codes, including all standard international (metric) prefixes from micro to mega. For example, denominational units of microcoins may be specified byµ฿
,u฿
,µB⃦
,µɃ
,µBTC
or other appropriate permutations of those characters. Additionally, if either or both of a custom currency code or symbol is configured usingBtcFormat.Builder.code
orBtcFormat.Builder.code
, then such code or symbol will be recognized in addition to those recognized by default.Instances of this class that recognize currency signs will recognize both currency symbols and codes, regardless of which that instance uses for formatting. However, if the style is
CODE
(and unless overridden by a custom pattern) then a space character must separate the units indicator from the number. When parsing with aSYMBOL
-styleBtcFormat
instance, on the other hand, whether or not the units indicator must be separated by a space from the number is determined by the locale. Thepattern()
method returns a representation of the pattern that can be examined to determine whether a space must separate currency signs from numbers in parsedString
s.When parsing, if the currency-units indicator is absent, then a
BtcAutoFormat
instance will infer a denomination of bitcoins while aBtcFixedFormat
will infer the denomination in which it expresses formatted values. Note: by default (unless overridden by a custom pattern), if the locale or style requires a space to separate the number from the units indicator, that space must be present in the String to be parsed, even if the units indicator is absent.The
parse()
method returns an instance of theCoin
class. Therefore, attempting to parse a value greater than the maximum that aCoin
object can represent will raise aParseException
, as will any other detected parsing error.Limitations
Parsing
Parsing is performed by an underlying
NumberFormat
object. While this delivers the benefit of recognizing locale-specific patterns, some have criticized other aspects of its behavior. For example, see this article by Joe Sam Shirah. In particular, explicit positive-signs are not recognized. If you are parsing input from end-users, then you should consider whether you would benefit from any of the work-arounds mentioned in that article.Exotic Locales
This class is not well-tested in locales that use non-ascii character sets, especially those where writing proceeds from right-to-left. Helpful feedback in that regard is appreciated.
Thread-Safety
Instances of this class are immutable.
- See Also:
Format
,NumberFormat
,DecimalFormat
,DecimalFormatSymbols
,FieldPosition
,Coin
, Serialized Form
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static class
BtcFormat.Builder
This class constructs new instances ofBtcFormat
, allowing for the configuration of those instances before they are constructed.
-
Field Summary
Fields Modifier and Type Field Description static int
COIN_SCALE
A constant useful for specifying a denomination of bitcoins, theint
value0
.protected static java.lang.String
COIN_SYMBOL_ALT
An alternative currency symbol to use in locales where the default symbol is used for the national currency.protected java.util.List<java.lang.Integer>
decimalGroups
static int
MICROCOIN_SCALE
A constant useful for specifying a denomination of microbitcoins, theint
value6
.static int
MILLICOIN_SCALE
A constant useful for specifying a denomination of millibitcoins, theint
value3
.protected int
minimumFractionDigits
protected java.text.DecimalFormat
numberFormat
-
Constructor Summary
Constructors Modifier Constructor Description protected
BtcFormat(java.text.DecimalFormat numberFormat, int minDecimals, java.util.List<java.lang.Integer> groups)
This single constructor is invoked by the overriding subclass constructors.
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Concrete Methods Modifier and Type Method Description static BtcFormat.Builder
builder()
Return a newBtcFormat.Builder
object.java.lang.String
coinCode()
Return the unprefixed international currency code for bitcoins configured for this object.java.lang.String
coinSymbol()
Return the unprefixed currency symbol for bitcoins configured for this object.boolean
equals(java.lang.Object o)
Return true if the given object is equivalent to this one.java.lang.String
format(java.lang.Object qty, int minDecimals, int... fractionGroups)
Formats a bitcoin value as a number and possibly a units indicator to aString
.The type of monetary value argument can be any one of any of the following classes:Coin
,Integer
,Long
,BigInteger
,BigDecimal
.java.lang.StringBuffer
format(java.lang.Object qty, java.lang.StringBuffer toAppendTo, java.text.FieldPosition pos)
Formats a bitcoin value as a number and possibly a units indicator and appends the resulting text to the given string buffer.java.lang.StringBuffer
format(java.lang.Object qty, java.lang.StringBuffer toAppendTo, java.text.FieldPosition pos, int minDecimals, int... fractionGroups)
Formats a bitcoin value as a number and possibly a units indicator and appends the resulting text to the given string buffer.java.text.AttributedCharacterIterator
formatToCharacterIterator(java.lang.Object obj)
Formats a bitcoin monetary value and returns anAttributedCharacterIterator
.static java.util.Locale[]
getAvailableLocales()
Return an array of all locales for which the getInstance() method of this class can return localized instances.static BtcFormat
getCodeInstance()
Return a new auto-denominating instance that will indicate units using a currency code, for example,"BTC"
.static BtcFormat
getCodeInstance(int minDecimals)
Return a new code-style auto-formatter with the given number of fractional decimal places.static BtcFormat
getCodeInstance(java.util.Locale locale)
Return a new code-style auto-formatter for the given locale.static BtcFormat
getCodeInstance(java.util.Locale locale, int minDecimals)
Return a new code-style auto-formatter for the given locale with the given number of fraction places.static BtcFormat
getCoinInstance()
Return a new coin-denominated formatter.static BtcFormat
getCoinInstance(int minFractionPlaces, int... groups)
Return a new coin-denominated formatter with the specified fraction-places.static BtcFormat
getCoinInstance(java.util.Locale locale)
Return a new coin-denominated formatter for the given locale.static BtcFormat
getCoinInstance(java.util.Locale locale, int scale, int... groups)
Return a newly-constructed instance for the given locale that will format values in terms of bitcoins, with the given minimum number of fractional decimal places.static BtcFormat
getInstance()
Return a new instance of this class using all defaults.static BtcFormat
getInstance(int scale)
Return a new fixed-denomination formatter.static BtcFormat
getInstance(int scale, int minDecimals, int... groups)
Return a new fixed-denomination formatter with the specified fractional decimal placing.static BtcFormat
getInstance(int scale, java.util.Locale locale)
Return a new fixed-denomination formatter for the given locale.static BtcFormat
getInstance(int scale, java.util.Locale locale, int minDecimals, int... groups)
Return a new fixed-denomination formatter for the given locale, with the specified fractional decimal placing.static BtcFormat
getInstance(int scale, java.util.Locale locale, int minDecimals, java.util.List<java.lang.Integer> groups)
Return a new fixed-denomination formatter for the given locale, with the specified fractional decimal placing.static BtcFormat
getInstance(java.util.Locale locale)
Return a new code-style auto-formatter for the given locale.static BtcFormat
getInstance(java.util.Locale locale, int minDecimals)
Return a new code-style auto-formatter for the given locale with the given number of fraction places.static BtcFormat
getInstance(BtcAutoFormat.Style style)
Return a new auto-denominating formatter.static BtcFormat
getInstance(BtcAutoFormat.Style style, int fractionPlaces)
Return a new auto-denominating formatter with the given number of fractional decimal places.static BtcFormat
getInstance(BtcAutoFormat.Style style, java.util.Locale locale)
Return a new auto-formatter with the given style for the given locale.static BtcFormat
getInstance(BtcAutoFormat.Style style, java.util.Locale locale, int fractionPlaces)
Return a new auto-formatter for the given locale with the given number of fraction places.static BtcFormat
getMicroInstance()
Return a new microcoin-denominated formatter for the default locale.static BtcFormat
getMicroInstance(int scale, int... groups)
Return a new microcoin-denominated formatter with the specified fractional decimal placing.static BtcFormat
getMicroInstance(java.util.Locale locale)
Return a new microcoin-denominated formatter for the given locale.static BtcFormat
getMicroInstance(java.util.Locale locale, int scale, int... groups)
Return a new microcoin-denominated formatter for the given locale with the specified fractional decimal placing.static BtcFormat
getMilliInstance()
Return a new millicoin-denominated formatter.static BtcFormat
getMilliInstance(int scale, int... groups)
Return a new millicoin-denominated formatter with the specified fractional decimal placing.static BtcFormat
getMilliInstance(java.util.Locale locale)
Return a new millicoin-denominated formatter for the given locale.static BtcFormat
getMilliInstance(java.util.Locale locale, int scale, int... groups)
Return a new millicoin-denominated formatter for the given locale with the specified fractional decimal placing.static BtcFormat
getSymbolInstance()
Return a new auto-denominating instance that will indicate units using a currency symbol, for example,"฿"
.static BtcFormat
getSymbolInstance(int fractionPlaces)
Return a new symbol-style auto-formatter with the given number of fractional decimal places.static BtcFormat
getSymbolInstance(java.util.Locale locale)
Return a new symbol-style auto-formatter for the given locale.static BtcFormat
getSymbolInstance(java.util.Locale locale, int fractionPlaces)
Return a new symbol-style auto-formatter for the given locale with the given number of fraction places.int
hashCode()
Return a hash code value for this instance.protected static java.lang.String
negify(java.lang.String pattern)
Guarantee a formatting pattern has a subpattern for negative values.Coin
parse(java.lang.String source)
Parse aString
representation of a Bitcoin monetary value.Coin
parse(java.lang.String source, java.text.ParsePosition pos)
Parse aString
representation of a Bitcoin monetary value.java.lang.Object
parseObject(java.lang.String source, java.text.ParsePosition pos)
Parse aString
representation of a Bitcoin monetary value.java.lang.String
pattern()
Return a representation of the pattern used by this instance for formatting and parsing.protected static java.lang.String
prefixCode(java.lang.String code, int scale)
END OF PARSING STUFFprotected static java.lang.String
prefixSymbol(java.lang.String symbol, int scale)
protected static void
prefixUnitsIndicator(java.text.DecimalFormat numberFormat, int scale)
Set both the currency symbol and code of the underlying, mutable NumberFormat object according to the given denominational units scale factor.protected abstract int
scale()
Return the denomination of this object.protected abstract int
scale(java.math.BigInteger satoshis, int fractionPlaces)
Return the denomination for formatting the given value.java.text.DecimalFormatSymbols
symbols()
Return a copy of the localized symbols used by this instance for formatting and parsing.
-
-
-
Field Detail
-
COIN_SYMBOL_ALT
protected static final java.lang.String COIN_SYMBOL_ALT
An alternative currency symbol to use in locales where the default symbol is used for the national currency.- See Also:
- Constant Field Values
-
numberFormat
protected final java.text.DecimalFormat numberFormat
-
minimumFractionDigits
protected final int minimumFractionDigits
-
decimalGroups
protected final java.util.List<java.lang.Integer> decimalGroups
-
COIN_SCALE
public static final int COIN_SCALE
A constant useful for specifying a denomination of bitcoins, theint
value0
.- See Also:
- Constant Field Values
-
MILLICOIN_SCALE
public static final int MILLICOIN_SCALE
A constant useful for specifying a denomination of millibitcoins, theint
value3
.- See Also:
- Constant Field Values
-
MICROCOIN_SCALE
public static final int MICROCOIN_SCALE
A constant useful for specifying a denomination of microbitcoins, theint
value6
.- See Also:
- Constant Field Values
-
-
Method Detail
-
builder
public static BtcFormat.Builder builder()
Return a newBtcFormat.Builder
object. See the documentation of that class for usage details.
-
getInstance
public static BtcFormat getInstance()
Return a new instance of this class using all defaults. The returned formatter will auto-denominate values so as to minimize zeros without loss of precision and display a currency code, for example "BTC
", to indicate that denomination. The returned object will uses the default locale for formatting the number and placement of the currency-code. Two fractional decimal places will be displayed in all formatted numbers.
-
getSymbolInstance
public static BtcFormat getSymbolInstance()
Return a new auto-denominating instance that will indicate units using a currency symbol, for example,"฿"
. Formatting and parsing will be done according to the default locale.
-
getCodeInstance
public static BtcFormat getCodeInstance()
Return a new auto-denominating instance that will indicate units using a currency code, for example,"BTC"
. Formatting and parsing will be done according to the default locale.
-
getSymbolInstance
public static BtcFormat getSymbolInstance(int fractionPlaces)
Return a new symbol-style auto-formatter with the given number of fractional decimal places. Denominational units will be indicated using a currency symbol, for example,"฿"
. The returned object will format the fraction-part of numbers using the given number of decimal places, or fewer as necessary to avoid giving a place to fractional satoshis. Formatting and parsing will be done according to the default locale.
-
getCodeInstance
public static BtcFormat getCodeInstance(int minDecimals)
Return a new code-style auto-formatter with the given number of fractional decimal places. Denominational units will be indicated using a currency code, for example,"BTC"
. The returned object will format the fraction-part of numbers using the given number of decimal places, or fewer as necessary to avoid giving a place to fractional satoshis. Formatting and parsing will be done according to the default locale.
-
getInstance
public static BtcFormat getInstance(java.util.Locale locale)
Return a new code-style auto-formatter for the given locale. The returned object will select denominational units based on each value being formatted, and will indicate those units using a currency code, for example,"mBTC"
.
-
getCodeInstance
public static BtcFormat getCodeInstance(java.util.Locale locale)
Return a new code-style auto-formatter for the given locale. The returned object will select denominational units based on each value being formatted, and will indicate those units using a currency code, for example,"mBTC"
.
-
getInstance
public static BtcFormat getInstance(java.util.Locale locale, int minDecimals)
Return a new code-style auto-formatter for the given locale with the given number of fraction places. The returned object will select denominational units based on each value being formatted, and will indicate those units using a currency code, for example,"mBTC"
. The returned object will format the fraction-part of numbers using the given number of decimal places, or fewer as necessary to avoid giving a place to fractional satoshis.
-
getCodeInstance
public static BtcFormat getCodeInstance(java.util.Locale locale, int minDecimals)
Return a new code-style auto-formatter for the given locale with the given number of fraction places. The returned object will select denominational units based on each value being formatted, and will indicate those units using a currency code, for example,"mBTC"
. The returned object will format the fraction-part of numbers using the given number of decimal places, or fewer as necessary to avoid giving a place to fractional satoshis.
-
getSymbolInstance
public static BtcFormat getSymbolInstance(java.util.Locale locale)
Return a new symbol-style auto-formatter for the given locale. The returned object will select denominational units based on each value being formatted, and will indicate those units using a currency symbol, for example,"µ฿"
.
-
getSymbolInstance
public static BtcFormat getSymbolInstance(java.util.Locale locale, int fractionPlaces)
Return a new symbol-style auto-formatter for the given locale with the given number of fraction places. The returned object will select denominational units based on each value being formatted, and will indicate those units using a currency symbol, for example,"µ฿"
. The returned object will format the fraction-part of numbers using the given number of decimal places, or fewer as necessary to avoid giving a place to fractional satoshis.
-
getInstance
public static BtcFormat getInstance(BtcAutoFormat.Style style)
Return a new auto-denominating formatter. The returned object will indicate the denominational units of formatted values using either a currency symbol, such as,"฿"
, or code, such as"mBTC"
, depending on the value of the argument. Formatting and parsing will be done according to the default locale.
-
getInstance
public static BtcFormat getInstance(BtcAutoFormat.Style style, int fractionPlaces)
Return a new auto-denominating formatter with the given number of fractional decimal places. The returned object will indicate the denominational units of formatted values using either a currency symbol, such as,"฿"
, or code, such as"mBTC"
, depending on the value of the first argument. The returned object will format the fraction-part of numbers using the given number of decimal places, or fewer as necessary to avoid giving a place to fractional satoshis. Formatting and parsing will be done according to the default locale.
-
getInstance
public static BtcFormat getInstance(BtcAutoFormat.Style style, java.util.Locale locale)
Return a new auto-formatter with the given style for the given locale. The returned object that will auto-denominate each formatted value, and will indicate that denomination using either a currency code, such as"BTC"
, or symbol, such as"฿"
, depending on the value of the first argument.The number of fractional decimal places in formatted number will be two, or fewer as necessary to avoid giving a place to fractional satoshis.
-
getInstance
public static BtcFormat getInstance(BtcAutoFormat.Style style, java.util.Locale locale, int fractionPlaces)
Return a new auto-formatter for the given locale with the given number of fraction places. The returned object will automatically-denominate each formatted value, and will indicate that denomination using either a currency code, such as"mBTC"
, or symbol, such as"฿"
, according to the given style argument. It will format each number according to the given locale.The third parameter is the number of fractional decimal places to use for each formatted number, reduced as necessary when formatting to avoid giving a place to fractional satoshis.
-
getCoinInstance
public static BtcFormat getCoinInstance()
Return a new coin-denominated formatter. The returned object will format and parse values according to the default locale, and will format numbers with two fractional decimal places, rounding values as necessary.
-
getCoinInstance
public static BtcFormat getCoinInstance(int minFractionPlaces, int... groups)
Return a new coin-denominated formatter with the specified fraction-places. The returned object will format and parse values according to the default locale, and will format the fraction part of numbers with at least two decimal places. The sizes of additional groups of decimal places can be specified by a variable number ofint
arguments. Each optional decimal-place group will be applied only if useful for expressing precision, and will be only partially applied if necessary to avoid giving a place to fractional satoshis.
-
getCoinInstance
public static BtcFormat getCoinInstance(java.util.Locale locale)
Return a new coin-denominated formatter for the given locale. The returned object will format the fractional part of numbers with two decimal places, rounding as necessary.
-
getCoinInstance
public static BtcFormat getCoinInstance(java.util.Locale locale, int scale, int... groups)
Return a newly-constructed instance for the given locale that will format values in terms of bitcoins, with the given minimum number of fractional decimal places. Optionally, repeating integer arguments can be passed, each indicating the size of an additional group of fractional decimal places to be used as necessary to avoid rounding, to a limiting precision of satoshis.
-
getMilliInstance
public static BtcFormat getMilliInstance()
Return a new millicoin-denominated formatter. The returned object will format and parse values for the default locale, and will format the fractional part of numbers with two decimal places, rounding as necessary.
-
getMilliInstance
public static BtcFormat getMilliInstance(java.util.Locale locale)
Return a new millicoin-denominated formatter for the given locale. The returned object will format the fractional part of numbers with two decimal places, rounding as necessary.
-
getMilliInstance
public static BtcFormat getMilliInstance(int scale, int... groups)
Return a new millicoin-denominated formatter with the specified fractional decimal placing. The returned object will format and parse values according to the default locale, and will format the fractional part of numbers with the given minimum number of fractional decimal places. Optionally, repeating integer arguments can be passed, each indicating the size of an additional group of fractional decimal places to be used as necessary to avoid rounding, to a limiting precision of satoshis.
-
getMilliInstance
public static BtcFormat getMilliInstance(java.util.Locale locale, int scale, int... groups)
Return a new millicoin-denominated formatter for the given locale with the specified fractional decimal placing. The returned object will format the fractional part of numbers with the given minimum number of fractional decimal places. Optionally, repeating integer arguments can be passed, each indicating the size of an additional group of fractional decimal places to be used as necessary to avoid rounding, to a limiting precision of satoshis.
-
getMicroInstance
public static BtcFormat getMicroInstance()
Return a new microcoin-denominated formatter for the default locale. The returned object will format the fractional part of numbers with two decimal places, rounding as necessary.
-
getMicroInstance
public static BtcFormat getMicroInstance(java.util.Locale locale)
Return a new microcoin-denominated formatter for the given locale. The returned object will format the fractional part of numbers with two decimal places, rounding as necessary.
-
getMicroInstance
public static BtcFormat getMicroInstance(int scale, int... groups)
Return a new microcoin-denominated formatter with the specified fractional decimal placing. The returned object will format and parse values according to the default locale, and will format the fractional part of numbers with the given minimum number of fractional decimal places. Optionally, repeating integer arguments can be passed, each indicating the size of an additional group of fractional decimal places to be used as necessary to avoid rounding, to a limiting precision of satoshis.
-
getMicroInstance
public static BtcFormat getMicroInstance(java.util.Locale locale, int scale, int... groups)
Return a new microcoin-denominated formatter for the given locale with the specified fractional decimal placing. The returned object will format the fractional part of numbers with the given minimum number of fractional decimal places. Optionally, repeating integer arguments can be passed, each indicating the size of an additional group of fractional decimal places to be used as necessary to avoid rounding, to a limiting precision of satoshis.
-
getInstance
public static BtcFormat getInstance(int scale, int minDecimals, int... groups)
Return a new fixed-denomination formatter with the specified fractional decimal placing. The first argument specifies the denomination as the size of the shift from coin-denomination in increasingly-precise decimal places. The returned object will format and parse values according to the default locale, and will format the fractional part of numbers with the given minimum number of fractional decimal places. Optionally, repeating integer arguments can be passed, each indicating the size of an additional group of fractional decimal places to be used as necessary to avoid rounding, to a limiting precision of satoshis.
-
getInstance
public static BtcFormat getInstance(int scale)
Return a new fixed-denomination formatter. The argument specifies the denomination as the size of the shift from coin-denomination in increasingly-precise decimal places. The returned object will format and parse values according to the default locale, and will format the fractional part of numbers with two decimal places, or fewer as necessary to avoid giving a place to fractional satoshis.
-
getInstance
public static BtcFormat getInstance(int scale, java.util.Locale locale)
Return a new fixed-denomination formatter for the given locale. The first argument specifies the denomination as the size of the shift from coin-denomination in increasingly-precise decimal places. The returned object will format and parse values according to the locale specified by the second argument, and will format the fractional part of numbers with two decimal places, or fewer as necessary to avoid giving a place to fractional satoshis.
-
getInstance
public static BtcFormat getInstance(int scale, java.util.Locale locale, int minDecimals, int... groups)
Return a new fixed-denomination formatter for the given locale, with the specified fractional decimal placing. The first argument specifies the denomination as the size of the shift from coin-denomination in increasingly-precise decimal places. The third parameter is the minimum number of fractional decimal places to use, followed by optional repeating integer parameters each specifying the size of an additional group of fractional decimal places to use as necessary to avoid rounding, down to a maximum precision of satoshis.
-
getInstance
public static BtcFormat getInstance(int scale, java.util.Locale locale, int minDecimals, java.util.List<java.lang.Integer> groups)
Return a new fixed-denomination formatter for the given locale, with the specified fractional decimal placing. The first argument specifies the denomination as the size of the shift from coin-denomination in increasingly-precise decimal places. The third parameter is the minimum number of fractional decimal places to use. The third argument specifies the minimum number of fractional decimal places in formatted numbers. The last argument is aList
ofInteger
values, each of which specifies the size of an additional group of fractional decimal places to use as necessary to avoid rounding, down to a maximum precision of satoshis.
-
formatToCharacterIterator
public java.text.AttributedCharacterIterator formatToCharacterIterator(java.lang.Object obj)
Formats a bitcoin monetary value and returns anAttributedCharacterIterator
. By iterating, you can examine what fields apply to each character. This can be useful since a character may be part of more than one field, for example a grouping separator that is also part of the integer field.- Overrides:
formatToCharacterIterator
in classjava.text.Format
- See Also:
AttributedCharacterIterator
-
format
public java.lang.StringBuffer format(java.lang.Object qty, java.lang.StringBuffer toAppendTo, java.text.FieldPosition pos)
Formats a bitcoin value as a number and possibly a units indicator and appends the resulting text to the given string buffer. The type of monetary value argument can be any one of any of the following classes:Coin
,Integer
,Long
,BigInteger
,BigDecimal
. Numeric types that can represent only an integer are interpreted as that number of satoshis. The value of aBigDecimal
is interpreted as that number of bitcoins, rounded to the nearest satoshi as necessary.- Specified by:
format
in classjava.text.Format
- Returns:
- the
StringBuffer
passed in astoAppendTo
-
format
public java.lang.String format(java.lang.Object qty, int minDecimals, int... fractionGroups)
Formats a bitcoin value as a number and possibly a units indicator to aString
.The type of monetary value argument can be any one of any of the following classes:Coin
,Integer
,Long
,BigInteger
,BigDecimal
. Numeric types that can represent only an integer are interpreted as that number of satoshis. The value of aBigDecimal
is interpreted as that number of bitcoins, rounded to the nearest satoshi as necessary.- Parameters:
minDecimals
- The minimum number of decimal places in the fractional part of the formatted numberfractionGroups
- The sizes of optional additional fractional decimal-place groups- Throws:
java.lang.IllegalArgumentException
- if the number of fraction places is negative.
-
format
public java.lang.StringBuffer format(java.lang.Object qty, java.lang.StringBuffer toAppendTo, java.text.FieldPosition pos, int minDecimals, int... fractionGroups)
Formats a bitcoin value as a number and possibly a units indicator and appends the resulting text to the given string buffer. The type of monetary value argument can be any one of any of the following classes:Coin
,Integer
,Long
,BigInteger
,BigDecimal
. Numeric types that can represent only an integer are interpreted as that number of satoshis. The value of aBigDecimal
is interpreted as that number of bitcoins, rounded to the nearest satoshi as necessary.- Parameters:
minDecimals
- The minimum number of decimal places in the fractional part of the formatted numberfractionGroups
- The sizes of optional additional fractional decimal-place groups- Throws:
java.lang.IllegalArgumentException
- if the number of fraction places is negative.
-
scale
protected abstract int scale(java.math.BigInteger satoshis, int fractionPlaces)
Return the denomination for formatting the given value. The returnedint
is the size of the decimal-place shift between the given Bitcoin-value denominated in bitcoins and that same value as formatted. A fixed-denomination formatter will ignore the arguments.- Parameters:
satoshis
- The number of satoshis having the value for which the shift is calculatedfractionPlaces
- The number of decimal places available for displaying the fractional part of the denominated value- Returns:
- The size of the shift in increasingly-precise decimal places
-
scale
protected abstract int scale()
Return the denomination of this object. Fixed-denomination formatters will override with their configured denomination, auto-formatters with coin denomination. This determines the interpretation of parsed numbers lacking a units-indicator.
-
parseObject
public final java.lang.Object parseObject(java.lang.String source, java.text.ParsePosition pos)
Parse aString
representation of a Bitcoin monetary value. Returns aCoin
object that represents the parsed value.- Specified by:
parseObject
in classjava.text.Format
- See Also:
NumberFormat
-
prefixUnitsIndicator
protected static void prefixUnitsIndicator(java.text.DecimalFormat numberFormat, int scale)
Set both the currency symbol and code of the underlying, mutable NumberFormat object according to the given denominational units scale factor. This is for formatting, not parsing.Set back to zero when you're done formatting otherwise immutability, equals() and hashCode() will break!
- Parameters:
scale
- Number of places the decimal point will be shifted when formatting a quantity of satoshis.
-
parse
public Coin parse(java.lang.String source, java.text.ParsePosition pos)
Parse aString
representation of a Bitcoin monetary value. If this object's pattern includes a currency sign, either symbol or code, as by default is true for instances ofBtcAutoFormat
and false for instances ofBtcFixedFormat
, then denominated (i.e., prefixed) currency signs in the parsed String will be recognized, and the parsed number will be interpreted as a quantity of units having that recognized denomination.If the pattern includes a currency sign but no currency sign is detected in the parsed String, then the number is interpreted as a quatity of bitcoins.
If the pattern contains neither a currency symbol nor sign, then instances of
BtcAutoFormat
will interpret the parsed number as a quantity of bitcoins, and instances ofBtcAutoFormat
will interpret the number as a quantity of that instance's configured denomination, which can be ascertained by invoking theBtcFixedFormat.symbol()
orBtcFixedFormat.code()
method.Consider using the single-argument version of this overloaded method unless you need to keep track of the current parse position.
- Returns:
- a Coin object representing the parsed value
- See Also:
ParsePosition
-
parse
public Coin parse(java.lang.String source) throws java.text.ParseException
Parse aString
representation of a Bitcoin monetary value. If this object's pattern includes a currency sign, either symbol or code, as by default is true for instances ofBtcAutoFormat
and false for instances ofBtcFixedFormat
, then denominated (i.e., prefixed) currency signs in the parsed String will be recognized, and the parsed number will be interpreted as a quantity of units having that recognized denomination.If the pattern includes a currency sign but no currency sign is detected in the parsed String, then the number is interpreted as a quatity of bitcoins.
If the pattern contains neither a currency symbol nor sign, then instances of
BtcAutoFormat
will interpret the parsed number as a quantity of bitcoins, and instances ofBtcAutoFormat
will interpret the number as a quantity of that instance's configured denomination, which can be ascertained by invoking theBtcFixedFormat.symbol()
orBtcFixedFormat.code()
method.- Returns:
- a Coin object representing the parsed value
- Throws:
java.text.ParseException
-
prefixCode
protected static java.lang.String prefixCode(java.lang.String code, int scale)
END OF PARSING STUFF
-
prefixSymbol
protected static java.lang.String prefixSymbol(java.lang.String symbol, int scale)
-
negify
protected static java.lang.String negify(java.lang.String pattern)
Guarantee a formatting pattern has a subpattern for negative values. This method takes a pattern that may be missing a negative subpattern, and returns the same pattern with a negative subpattern appended as needed.This method accommodates an imperfection in the Java formatting code and distributed locale data. To wit: the subpattern for negative numbers is optional and not all locales have one. In those cases,
DecimalFormat
will indicate numbers less than zero by adding a negative sign as the first character of the prefix of the positive subpattern.We don't like this, since we claim the negative sign applies to the number not the units, and therefore it ought to be adjacent to the number, displacing the currency-units indicator if necessary.
-
getAvailableLocales
public static java.util.Locale[] getAvailableLocales()
Return an array of all locales for which the getInstance() method of this class can return localized instances. SeeNumberFormat.getAvailableLocales()
-
coinSymbol
public java.lang.String coinSymbol()
Return the unprefixed currency symbol for bitcoins configured for this object. The return value of this method is constant throughout the life of an instance.
-
coinCode
public java.lang.String coinCode()
Return the unprefixed international currency code for bitcoins configured for this object. The return value of this method is constant throughough the life of an instance.
-
pattern
public java.lang.String pattern()
Return a representation of the pattern used by this instance for formatting and parsing. The format is similar to, but not the same as the format recognized by theBtcFormat.Builder.pattern
andBtcFormat.Builder.localizedPattern
methods. The pattern returned by this method is localized, any currency signs expressed are literally, and optional fractional decimal places are shown grouped in parentheses.
-
symbols
public java.text.DecimalFormatSymbols symbols()
Return a copy of the localized symbols used by this instance for formatting and parsing.
-
equals
public boolean equals(java.lang.Object o)
Return true if the given object is equivalent to this one. Formatters for different locales will never be equal, even if they behave identically.- Overrides:
equals
in classjava.lang.Object
-
hashCode
public int hashCode()
Return a hash code value for this instance.- Overrides:
hashCode
in classjava.lang.Object
- See Also:
Object.hashCode()
-
-