Configure CoinFormat with values from a Locale.

This commit is contained in:
Andreas Schildbach 2014-08-24 23:37:23 +02:00
parent 9e91c54fdd
commit f3733cae3b
2 changed files with 26 additions and 1 deletions

View File

@ -23,6 +23,7 @@ import static com.google.common.math.LongMath.checkedPow;
import static com.google.common.math.LongMath.divide;
import java.math.RoundingMode;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@ -275,6 +276,18 @@ public final class CoinFormat {
shift, roundingMode, codes, codeSeparator, false);
}
/**
* Configure this instance with values from a {@link Locale}.
*/
public CoinFormat withLocale(Locale locale) {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(locale);
char negativeSign = dfs.getMinusSign();
char zeroDigit = dfs.getZeroDigit();
char decimalMark = dfs.getMonetaryDecimalSeparator();
return new CoinFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift,
roundingMode, codes, codeSeparator, codePrefixed);
}
public CoinFormat() {
// defaults
this.negativeSign = '-';
@ -419,7 +432,7 @@ public final class CoinFormat {
for (char c : satoshis.toCharArray())
if (!Character.isDigit(c))
throw new NumberFormatException("illegal character: " + c);
long value = Long.parseLong(satoshis);
long value = Long.parseLong(satoshis); // non-arabic digits allowed here
if (first == negativeSign)
value = -value;
return value;

View File

@ -22,6 +22,8 @@ import static com.google.bitcoin.core.Coin.SATOSHI;
import static com.google.bitcoin.core.Coin.ZERO;
import static org.junit.Assert.assertEquals;
import java.util.Locale;
import org.junit.Test;
import com.google.bitcoin.core.Coin;
@ -234,6 +236,14 @@ public class CoinFormatTest {
CoinFormat.UBTC.shift(1).format(Coin.ZERO);
}
@Test
public void withLocale() throws Exception {
final Coin value = Coin.valueOf(-1234567890l);
assertEquals("-12.34567890", NO_CODE.withLocale(Locale.US).format(value).toString());
assertEquals("-12,34567890", NO_CODE.withLocale(Locale.GERMANY).format(value).toString());
assertEquals("-१२.३४५६७८९०", NO_CODE.withLocale(new Locale("hi", "IN")).format(value).toString()); // Devanagari
}
@Test
public void parse() throws Exception {
assertEquals(Coin.COIN, NO_CODE.parse("1"));
@ -260,6 +270,8 @@ public class CoinFormatTest {
assertEquals(Coin.MICROCOIN, CoinFormat.UBTC.positiveSign('+').parse("+1.0"));
assertEquals(Coin.MICROCOIN.negate(), CoinFormat.UBTC.parse("-1"));
assertEquals(Coin.MICROCOIN.negate(), CoinFormat.UBTC.parse("-1.0"));
assertEquals(Coin.CENT, NO_CODE.withLocale(new Locale("hi", "IN")).parse(".०१")); // Devanagari
}
@Test(expected = NumberFormatException.class)