updates with formatting

This commit is contained in:
Manfred Karrer 2014-08-28 12:53:27 +02:00
parent 56ca79a58f
commit a8c3040fb3
9 changed files with 224 additions and 91 deletions

View file

@ -122,7 +122,7 @@ public class BalanceTextField extends AnchorPane {
} }
private void updateBalance(Coin balance) { private void updateBalance(Coin balance) {
balanceTextField.setText(BSFormatter.formatBtc(balance)); balanceTextField.setText(BSFormatter.formatCoin(balance));
} }
} }

View file

@ -148,7 +148,7 @@ public class WithdrawalController extends CachedViewController {
amountTextField, withdrawFromTextField, withdrawToTextField, changeAddressTextField); amountTextField, withdrawFromTextField, withdrawToTextField, changeAddressTextField);
BitSquareValidator.textFieldsHasDoubleValueWithReset(amountTextField); BitSquareValidator.textFieldsHasDoubleValueWithReset(amountTextField);
Coin amount = BSFormatter.parseToBtc(amountTextField.getText()); Coin amount = BSFormatter.parseToCoin(amountTextField.getText());
if (Restrictions.isMinSpendableAmount(amount)) { if (Restrictions.isMinSpendableAmount(amount)) {
FutureCallback<Transaction> callback = new FutureCallback<Transaction>() { FutureCallback<Transaction> callback = new FutureCallback<Transaction>() {
@Override @Override

View file

@ -105,7 +105,7 @@ class CreateOfferPresenter {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
void onViewInitialized() { void onViewInitialized() {
totalFees.set(BSFormatter.formatBtc(model.totalFeesAsCoin)); totalFees.set(BSFormatter.formatCoin(model.totalFeesAsCoin));
paymentLabel.set("Bitsquare trade (" + model.getOfferId() + ")"); paymentLabel.set("Bitsquare trade (" + model.getOfferId() + ")");
if (model.addressEntry != null) { if (model.addressEntry != null) {
@ -166,8 +166,8 @@ class CreateOfferPresenter {
model.priceAsFiat = parseToFiatWith2Decimals(String.valueOf(orderBookFilter.getPrice())); model.priceAsFiat = parseToFiatWith2Decimals(String.valueOf(orderBookFilter.getPrice()));
directionLabel.set(model.getDirection() == Direction.BUY ? "Buy:" : "Sell:"); directionLabel.set(model.getDirection() == Direction.BUY ? "Buy:" : "Sell:");
amount.set(formatBtc(model.amountAsCoin)); amount.set(formatCoin(model.amountAsCoin));
minAmount.set(formatBtc(model.minAmountAsCoin)); minAmount.set(formatCoin(model.minAmountAsCoin));
price.set(formatFiat(model.priceAsFiat)); price.set(formatFiat(model.priceAsFiat));
} }
@ -177,10 +177,10 @@ class CreateOfferPresenter {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
void placeOffer() { void placeOffer() {
model.amountAsCoin = parseToBtcWith4Decimals(amount.get()); model.amountAsCoin = parseToCoinWith4Decimals(amount.get());
model.minAmountAsCoin = parseToBtcWith4Decimals(minAmount.get()); model.minAmountAsCoin = parseToCoinWith4Decimals(minAmount.get());
model.priceAsFiat = parseToFiatWith2Decimals(price.get()); model.priceAsFiat = parseToFiatWith2Decimals(price.get());
model.minAmountAsCoin = parseToBtcWith4Decimals(minAmount.get()); model.minAmountAsCoin = parseToCoinWith4Decimals(minAmount.get());
needsInputValidation.set(true); needsInputValidation.set(true);
@ -202,19 +202,23 @@ class CreateOfferPresenter {
// bindBidirectional for amount, price, volume and minAmount // bindBidirectional for amount, price, volume and minAmount
amount.addListener(ov -> { amount.addListener(ov -> {
model.amountAsCoin = parseToBtcWith4Decimals(amount.get()); model.amountAsCoin = parseToCoinWith4Decimals(amount.get());
calculateVolume();
calculateTotalToPay(); calculateTotalToPay();
calculateCollateral(); calculateCollateral();
}); });
price.addListener(ov -> { price.addListener(ov -> {
model.priceAsFiat = parseToFiatWith2Decimals(price.get()); model.priceAsFiat = parseToFiatWith2Decimals(price.get());
calculateVolume();
calculateTotalToPay(); calculateTotalToPay();
calculateCollateral(); calculateCollateral();
}); });
volume.addListener(ov -> { volume.addListener(ov -> {
model.volumeAsFiat = parseToFiatWith2Decimals(volume.get()); model.volumeAsFiat = parseToFiatWith2Decimals(volume.get());
calculateAmount();
calculateTotalToPay(); calculateTotalToPay();
calculateCollateral(); calculateCollateral();
}); });
@ -224,8 +228,8 @@ class CreateOfferPresenter {
if (oldValue && !newValue) { if (oldValue && !newValue) {
showWarningInvalidBtcDecimalPlaces.set(!hasBtcValidDecimals(amount.get())); showWarningInvalidBtcDecimalPlaces.set(!hasBtcValidDecimals(amount.get()));
model.amountAsCoin = parseToBtcWith4Decimals(amount.get()); model.amountAsCoin = parseToCoinWith4Decimals(amount.get());
amount.set(formatBtc(model.amountAsCoin)); amount.set(formatCoin(model.amountAsCoin));
calculateVolume(); calculateVolume();
} }
} }
@ -234,8 +238,8 @@ class CreateOfferPresenter {
if (oldValue && !newValue) { if (oldValue && !newValue) {
showWarningInvalidBtcDecimalPlaces.set(!hasBtcValidDecimals(minAmount.get())); showWarningInvalidBtcDecimalPlaces.set(!hasBtcValidDecimals(minAmount.get()));
model.minAmountAsCoin = parseToBtcWith4Decimals(minAmount.get()); model.minAmountAsCoin = parseToCoinWith4Decimals(minAmount.get());
minAmount.set(formatBtc(model.minAmountAsCoin)); minAmount.set(formatCoin(model.minAmountAsCoin));
} }
} }
@ -280,7 +284,7 @@ class CreateOfferPresenter {
} }
private void calculateVolume() { private void calculateVolume() {
model.amountAsCoin = parseToBtcWith4Decimals(amount.get()); model.amountAsCoin = parseToCoinWith4Decimals(amount.get());
model.priceAsFiat = parseToFiatWith2Decimals(price.get()); model.priceAsFiat = parseToFiatWith2Decimals(price.get());
if (model.priceAsFiat != null && model.amountAsCoin != null && !model.amountAsCoin.isZero()) { if (model.priceAsFiat != null && model.amountAsCoin != null && !model.amountAsCoin.isZero()) {
@ -298,7 +302,7 @@ class CreateOfferPresenter {
// If we got a btc value with more then 4 decimals we convert it to max 4 decimals // If we got a btc value with more then 4 decimals we convert it to max 4 decimals
model.amountAsCoin = reduceto4Dezimals(model.amountAsCoin); model.amountAsCoin = reduceto4Dezimals(model.amountAsCoin);
amount.set(formatBtc(model.amountAsCoin)); amount.set(formatCoin(model.amountAsCoin));
calculateTotalToPay(); calculateTotalToPay();
calculateCollateral(); calculateCollateral();
} }
@ -309,7 +313,7 @@ class CreateOfferPresenter {
if (model.collateralAsCoin != null) { if (model.collateralAsCoin != null) {
model.totalToPayAsCoin.set(model.collateralAsCoin.add(model.totalFeesAsCoin)); model.totalToPayAsCoin.set(model.collateralAsCoin.add(model.totalFeesAsCoin));
totalToPay.bind(createStringBinding(() -> formatBtcWithCode(model.totalToPayAsCoin.get()), totalToPay.bind(createStringBinding(() -> formatCoinWithCode(model.totalToPayAsCoin.get()),
model.totalToPayAsCoin)); model.totalToPayAsCoin));
} }
} }
@ -317,7 +321,7 @@ class CreateOfferPresenter {
private void calculateCollateral() { private void calculateCollateral() {
if (model.amountAsCoin != null) { if (model.amountAsCoin != null) {
model.collateralAsCoin = model.amountAsCoin.multiply(model.collateralAsLong.get()).divide(1000); model.collateralAsCoin = model.amountAsCoin.multiply(model.collateralAsLong.get()).divide(1000);
collateral.set(BSFormatter.formatBtcWithCode(model.collateralAsCoin)); collateral.set(BSFormatter.formatCoinWithCode(model.collateralAsCoin));
} }
} }
} }

View file

@ -187,7 +187,7 @@ public class OrderBookController extends CachedViewController {
// handlers // handlers
amount.textProperty().addListener((observable, oldValue, newValue) -> { amount.textProperty().addListener((observable, oldValue, newValue) -> {
orderBookFilter.setAmount(BSFormatter.parseToBtc(newValue)); orderBookFilter.setAmount(BSFormatter.parseToCoin(newValue));
updateVolume(); updateVolume();
}); });
@ -348,7 +348,7 @@ public class OrderBookController extends CachedViewController {
Coin requestedAmount; Coin requestedAmount;
if (!"".equals(amount.getText())) { if (!"".equals(amount.getText())) {
requestedAmount = BSFormatter.parseToBtc(amount.getText()); requestedAmount = BSFormatter.parseToCoin(amount.getText());
} }
else { else {
requestedAmount = offer.getAmount(); requestedAmount = offer.getAmount();

View file

@ -153,7 +153,7 @@ public class TakeOfferController extends CachedViewController {
@FXML @FXML
public void onTakeOffer() { public void onTakeOffer() {
AddressEntry addressEntry = walletFacade.getAddressInfoByTradeID(offer.getId()); AddressEntry addressEntry = walletFacade.getAddressInfoByTradeID(offer.getId());
Coin amount = BSFormatter.parseToBtc(getAmountString()); Coin amount = BSFormatter.parseToCoin(getAmountString());
// TODO more validation (fee payment, blacklist,...) // TODO more validation (fee payment, blacklist,...)
if (amountTextField.isInvalid()) { if (amountTextField.isInvalid()) {
Popups.openErrorPopup("Invalid input", "The requested amount you entered is not a valid amount."); Popups.openErrorPopup("Invalid input", "The requested amount you entered is not a valid amount.");
@ -279,7 +279,7 @@ public class TakeOfferController extends CachedViewController {
} }
private Coin getAmountInSatoshis() { private Coin getAmountInSatoshis() {
return BSFormatter.parseToBtc(getAmountString()); return BSFormatter.parseToCoin(getAmountString());
} }
private String getAmountString() { private String getAmountString() {
@ -304,12 +304,12 @@ public class TakeOfferController extends CachedViewController {
} }
private Coin getCollateralAsCoin() { private Coin getCollateralAsCoin() {
Coin amountAsCoin = BSFormatter.parseToBtc(getAmountString()); Coin amountAsCoin = BSFormatter.parseToCoin(getAmountString());
return amountAsCoin.divide((long) (1d / offer.getCollateral())); return amountAsCoin.divide((long) (1d / offer.getCollateral()));
} }
private String getFormattedCollateralAsBtc() { private String getFormattedCollateralAsBtc() {
Coin amountAsCoin = BSFormatter.parseToBtc(getAmountString()); Coin amountAsCoin = BSFormatter.parseToCoin(getAmountString());
Coin collateralAsCoin = amountAsCoin.divide((long) (1d / getCollateral())); Coin collateralAsCoin = amountAsCoin.divide((long) (1d / getCollateral()));
return BSFormatter.formatCoin(collateralAsCoin); return BSFormatter.formatCoin(collateralAsCoin);
} }

View file

@ -23,6 +23,7 @@ import io.bitsquare.locale.Localisation;
import io.bitsquare.trade.Direction; import io.bitsquare.trade.Direction;
import com.google.bitcoin.core.Coin; import com.google.bitcoin.core.Coin;
import com.google.bitcoin.utils.BtcFormat;
import com.google.bitcoin.utils.CoinFormat; import com.google.bitcoin.utils.CoinFormat;
import com.google.bitcoin.utils.Fiat; import com.google.bitcoin.utils.Fiat;
@ -42,9 +43,21 @@ import org.slf4j.LoggerFactory;
import static com.google.common.base.Preconditions.*; import static com.google.common.base.Preconditions.*;
//TODO a lot of old trash... need to cleanup... //TODO a lot of old trash... need to cleanup...
/**
* Central point for formatting and input parsing.
* <p>
* Note that we never use for text input values any coin or currency symbol or code.
* BtcFormat does not support
*/
public class BSFormatter { public class BSFormatter {
private static final Logger log = LoggerFactory.getLogger(BSFormatter.class); private static final Logger log = LoggerFactory.getLogger(BSFormatter.class);
private static Locale locale = Locale.getDefault();
private static boolean useMilliBit;
private static String code = "BTC";
private static int scale = 3;
// format is like: 1,00 or 1,0010 never more then 4 decimals // format is like: 1,00 or 1,0010 never more then 4 decimals
private static CoinFormat coinFormat = CoinFormat.BTC.repeatOptionalDecimals(2, 1); private static CoinFormat coinFormat = CoinFormat.BTC.repeatOptionalDecimals(2, 1);
@ -52,28 +65,40 @@ public class BSFormatter {
private static CoinFormat fiatFormat = CoinFormat.FIAT.repeatOptionalDecimals(0, 0); private static CoinFormat fiatFormat = CoinFormat.FIAT.repeatOptionalDecimals(0, 0);
private static String currencyCode = Currency.getInstance(Locale.getDefault()).getCurrencyCode(); private static String currencyCode = Currency.getInstance(Locale.getDefault()).getCurrencyCode();
private static Locale locale = Locale.getDefault();
private static BtcFormat btcFormat = getBtcFormat();
static {
//useMilliBitFormat(true);
}
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// Config // Config
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
public static void useMilliBitFormat() {
coinFormat = CoinFormat.MBTC.repeatOptionalDecimals(2, 1);
}
public static void setFiatCurrencyCode(String currencyCode) { public static void useMilliBitFormat(boolean useMilliBit) {
BSFormatter.currencyCode = currencyCode; BSFormatter.useMilliBit = useMilliBit;
code = useMilliBit ? "mBTC" : "BTC";
btcFormat = getBtcFormat();
scale = useMilliBit ? 0 : 3;
} }
/** /**
* Note that setting the locale does not set the currency as it might be independent. * Note that setting the locale does not set the currency as it might be independent.
*
* @param locale
*/ */
public static void setLocale(Locale locale) { public static void setLocale(Locale locale) {
BSFormatter.locale = locale; BSFormatter.locale = locale;
btcFormat = getBtcFormat();
}
private static BtcFormat getBtcFormat() {
return BtcFormat.getInstance(useMilliBit ? BtcFormat.MILLICOIN_SCALE : BtcFormat.COIN_SCALE, locale, 2, 2);
}
public static void setFiatCurrencyCode(String currencyCode) {
BSFormatter.currencyCode = currencyCode;
} }
@ -81,31 +106,31 @@ public class BSFormatter {
// BTC // BTC
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
public static String formatBtc(Coin coin) { public static String formatCoin(Coin coin) {
try { try {
return coinFormat.noCode().format(coin).toString(); return btcFormat.format(coin);
} catch (Throwable t) { } catch (Throwable t) {
log.warn("Exception at formatBtc: " + t.toString()); log.warn("Exception at formatBtc: " + t.toString());
return ""; return "";
} }
} }
public static String formatBtcWithCode(Coin coin) { public static String formatCoinWithCode(Coin coin) {
try { try {
return coinFormat.postfixCode().format(coin).toString(); // we don't use the code feature from btcFormat as it does automatic switching between mBTC and BTC and
// pre and post fixing
return btcFormat.format(coin) + " " + code;
} catch (Throwable t) { } catch (Throwable t) {
log.warn("Exception at formatBtcWithCode: " + t.toString()); log.warn("Exception at formatBtcWithCode: " + t.toString());
return ""; return "";
} }
} }
public static Coin parseToBtc(String input) { public static Coin parseToCoin(String input) {
try { try {
input = input.replace(",", "."); return btcFormat.parse(input);
Double.parseDouble(input); // test if valid double
return Coin.parseCoin(input);
} catch (Throwable t) { } catch (Throwable t) {
log.warn("Exception at parseToCoin: " + t.toString()); log.warn("Exception at parseToBtc: " + t.toString());
return Coin.ZERO; return Coin.ZERO;
} }
} }
@ -118,20 +143,18 @@ public class BSFormatter {
* @param input * @param input
* @return * @return
*/ */
public static Coin parseToBtcWith4Decimals(String input) { public static Coin parseToCoinWith4Decimals(String input) {
try { try {
input = input.replace(",", "."); return Coin.valueOf(new BigDecimal(parseToCoin(input).value).setScale(-scale - 1,
Double.parseDouble(input); // test if valid double BigDecimal.ROUND_HALF_UP).setScale(scale + 1).toBigInteger().longValue());
return parseToBtc(new BigDecimal(input).setScale(4, BigDecimal.ROUND_HALF_UP).toString());
} catch (Throwable t) { } catch (Throwable t) {
log.warn("Exception at parseCoinTo4Decimals: " + t.toString()); log.warn("Exception at parseToCoinWith4Decimals: " + t.toString());
return Coin.ZERO; return Coin.ZERO;
} }
} }
public static boolean hasBtcValidDecimals(String input) { public static boolean hasBtcValidDecimals(String input) {
return parseToBtc(input).equals(parseToBtcWith4Decimals(input)); return parseToCoin(input).equals(parseToCoinWith4Decimals(input));
} }
/** /**
@ -141,7 +164,7 @@ public class BSFormatter {
* @return The transformed coin * @return The transformed coin
*/ */
public static Coin reduceto4Dezimals(Coin coin) { public static Coin reduceto4Dezimals(Coin coin) {
return parseToBtc(formatBtc(coin)); return parseToCoin(formatCoin(coin));
} }
@ -323,7 +346,7 @@ public class BSFormatter {
public static String formatVolumeWithMinVolume(double volume, double minVolume) { public static String formatVolumeWithMinVolume(double volume, double minVolume) {
return formatDouble(volume) + " (" + formatDouble(minVolume) + ")"; return formatDouble(volume) + " (" + formatDouble(minVolume) + ")";
} }
/*
@Deprecated @Deprecated
public static String formatCoin(Coin coin) { public static String formatCoin(Coin coin) {
return coin != null ? coin.toPlainString() : ""; return coin != null ? coin.toPlainString() : "";
@ -333,5 +356,5 @@ public class BSFormatter {
@Deprecated @Deprecated
public static String formatCoinWithCode(Coin coin) { public static String formatCoinWithCode(Coin coin) {
return coin != null ? coin.toFriendlyString() : ""; return coin != null ? coin.toFriendlyString() : "";
} }*/
} }

View file

@ -26,7 +26,7 @@ import io.bitsquare.trade.handlers.TransactionResultHandler;
import io.bitsquare.trade.protocol.createoffer.tasks.BroadCastOfferFeeTx; import io.bitsquare.trade.protocol.createoffer.tasks.BroadCastOfferFeeTx;
import io.bitsquare.trade.protocol.createoffer.tasks.CreateOfferFeeTx; import io.bitsquare.trade.protocol.createoffer.tasks.CreateOfferFeeTx;
import io.bitsquare.trade.protocol.createoffer.tasks.PublishOfferToDHT; import io.bitsquare.trade.protocol.createoffer.tasks.PublishOfferToDHT;
import io.bitsquare.trade.protocol.createoffer.tasks.ValidateOffer; import io.bitsquare.trade.protocol.createoffer.tasks.VerifyOffer;
import com.google.bitcoin.core.Transaction; import com.google.bitcoin.core.Transaction;
@ -112,7 +112,7 @@ public class CreateOfferCoordinator {
public void start() { public void start() {
model.setState(State.STARTED); model.setState(State.STARTED);
ValidateOffer.run(this::onOfferValidated, this::onFailed, offer); VerifyOffer.run(this::onOfferValidated, this::onFailed, offer);
} }
private void onOfferValidated() { private void onOfferValidated() {

View file

@ -30,33 +30,35 @@ import org.slf4j.LoggerFactory;
import static com.google.common.base.Preconditions.*; import static com.google.common.base.Preconditions.*;
@Immutable @Immutable
public class ValidateOffer { public class VerifyOffer {
private static final Logger log = LoggerFactory.getLogger(ValidateOffer.class); private static final Logger log = LoggerFactory.getLogger(VerifyOffer.class);
public static void run(ResultHandler resultHandler, FaultHandler faultHandler, Offer offer) { public static void run(ResultHandler resultHandler, FaultHandler faultHandler, Offer offer) {
try { try {
checkNotNull(offer.getAcceptedCountries()); checkNotNull(offer.getAcceptedCountries(), "AcceptedCountries is null");
checkNotNull(offer.getAcceptedLanguageLocales()); checkNotNull(offer.getAcceptedLanguageLocales(), "AcceptedLanguageLocales is null");
checkNotNull(offer.getAmount()); checkNotNull(offer.getAmount(), "Amount is null");
checkNotNull(offer.getArbitrator()); checkNotNull(offer.getArbitrator(), "Arbitrator is null");
checkNotNull(offer.getBankAccountCountry()); checkNotNull(offer.getBankAccountCountry(), "BankAccountCountry is null");
checkNotNull(offer.getBankAccountId()); checkNotNull(offer.getBankAccountId(), "BankAccountId is null");
checkNotNull(offer.getCollateral()); checkNotNull(offer.getCollateral(), "Collateral is null");
checkNotNull(offer.getCreationDate()); checkNotNull(offer.getCreationDate(), "CreationDate is null");
checkNotNull(offer.getCurrency()); checkNotNull(offer.getCurrency(), "Currency is null");
checkNotNull(offer.getDirection()); checkNotNull(offer.getDirection(), "Direction is null");
checkNotNull(offer.getId()); checkNotNull(offer.getId(), "Id is null");
checkNotNull(offer.getMessagePublicKey()); checkNotNull(offer.getMessagePublicKey(), "MessagePublicKey is null");
checkNotNull(offer.getMinAmount()); checkNotNull(offer.getMinAmount(), "MinAmount is null");
checkNotNull(offer.getPrice()); checkNotNull(offer.getPrice(), "Price is null");
checkArgument(offer.getAcceptedCountries().size() > 0); checkArgument(!offer.getAcceptedCountries().isEmpty(), "AcceptedCountries is empty");
checkArgument(offer.getAcceptedLanguageLocales().size() > 0); checkArgument(!offer.getAcceptedLanguageLocales().isEmpty(), "AcceptedLanguageLocales is empty");
checkArgument(offer.getMinAmount().compareTo(Restrictions.MIN_TRADE_AMOUNT) >= 0); checkArgument(offer.getMinAmount().compareTo(Restrictions.MIN_TRADE_AMOUNT) >= 0,
checkArgument(offer.getAmount().compareTo(Restrictions.MIN_TRADE_AMOUNT) >= 0); "MinAmount is less then " + Restrictions.MIN_TRADE_AMOUNT);
checkArgument(offer.getAmount().compareTo(offer.getMinAmount()) >= 0); checkArgument(offer.getAmount().compareTo(Restrictions.MIN_TRADE_AMOUNT) >= 0,
checkArgument(offer.getCollateral() > 0); "Amount is less then " + Restrictions.MIN_TRADE_AMOUNT);
checkArgument(offer.getPrice() > 0); checkArgument(offer.getAmount().compareTo(offer.getMinAmount()) >= 0, "MinAmount is larger then Amount");
checkArgument(offer.getCollateral() > 0, "Collateral is 0");
checkArgument(offer.getPrice() > 0, "Price is 0");
// TODO check balance // TODO check balance
// Coin collateralAsCoin = offer.getAmount().divide((long) (1d / offer.getCollateral())); // Coin collateralAsCoin = offer.getAmount().divide((long) (1d / offer.getCollateral()));

View file

@ -17,6 +17,10 @@
package io.bitsquare.gui.util; package io.bitsquare.gui.util;
import com.google.bitcoin.core.Coin;
import java.util.Locale;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -29,18 +33,115 @@ public class BSFormatterTest {
private static final Logger log = LoggerFactory.getLogger(BSFormatterTest.class); private static final Logger log = LoggerFactory.getLogger(BSFormatterTest.class);
@Test @Test
public void testParseToBtcWith4Decimals() { public void testParseToBtc() {
useMilliBitFormat(false);
setLocale(Locale.GERMAN);
assertEquals(Coin.ZERO, parseToCoin("0"));
assertEquals(Coin.COIN, parseToCoin("1"));
assertEquals(Coin.SATOSHI, parseToCoin("0,00000001"));
assertEquals("0", parseToBtcWith4Decimals("0").toPlainString()); assertEquals(Coin.parseCoin("-1"), parseToCoin("-1"));
assertEquals("0", parseToBtcWith4Decimals(null).toPlainString()); assertEquals(Coin.parseCoin("1.1"), parseToCoin("1,1"));
assertEquals("0", parseToBtcWith4Decimals("s").toPlainString()); assertEquals(Coin.parseCoin("11"), parseToCoin("1.1"));
assertEquals("0.0012", parseToBtcWith4Decimals("0.00123").toPlainString()); assertEquals(Coin.parseCoin("1123.45"), parseToCoin("1.123,45"));
assertEquals("0.0013", parseToBtcWith4Decimals("0.00125").toPlainString()); assertEquals(Coin.parseCoin("1.123"), parseToCoin("1,123.45"));
assertEquals("0.0013", parseToBtcWith4Decimals("0,00125").toPlainString());
assertEquals(Coin.parseCoin("1.1234"), parseToCoinWith4Decimals("1,12342"));
assertEquals(Coin.parseCoin("1.1235"), parseToCoinWith4Decimals("1,12345"));
assertEquals(Coin.parseCoin("1.1230"), parseToCoinWith4Decimals("1,123"));
// change locale
setLocale(Locale.US);
assertEquals(Coin.parseCoin("1.1"), parseToCoin("1.1"));
assertEquals(Coin.parseCoin("11"), parseToCoin("1,1"));
assertEquals(Coin.parseCoin("1.123"), parseToCoin("1.123,45"));
assertEquals(Coin.parseCoin("1123.45"), parseToCoin("1,123.45"));
// change to mBTC
useMilliBitFormat(true);
assertEquals(Coin.parseCoin("1"), parseToCoin("1000"));
assertEquals(Coin.parseCoin("0.123"), parseToCoin("123"));
assertEquals(Coin.parseCoin("0.1234"), parseToCoin("123.4"));
assertEquals(Coin.parseCoin("0.12345"), parseToCoin("123.45"));
assertEquals(Coin.parseCoin("0.123456"), parseToCoin("123.456"));
assertEquals(Coin.parseCoin("123.4567"), parseToCoin("123,456.7"));
assertEquals(Coin.parseCoin("0.001123"), parseToCoinWith4Decimals("1.123"));
assertEquals(Coin.parseCoin("0.0011234"), parseToCoinWith4Decimals("1.1234"));
assertEquals(Coin.parseCoin("0.0011234"), parseToCoinWith4Decimals("1.12342"));
assertEquals(Coin.parseCoin("0.0011235"), parseToCoinWith4Decimals("1.12345"));
} }
@Test
public void testFormatCoin() {
useMilliBitFormat(false);
setLocale(Locale.GERMAN);
assertEquals("1,00", formatCoin(Coin.COIN));
assertEquals("1,0120", formatCoin(Coin.parseCoin("1.012")));
assertEquals("1.012,30", formatCoin(Coin.parseCoin("1012.3")));
assertEquals("1,0120", formatCoin(Coin.parseCoin("1.01200")));
assertEquals("1,0123", formatCoin(Coin.parseCoin("1.01234")));
assertEquals("1,2345", formatCoin(Coin.parseCoin("1.2345")));
assertEquals("1,2346", formatCoin(Coin.parseCoin("1.23456")));
assertEquals("1,2346", formatCoin(Coin.parseCoin("1.234567")));
assertEquals("1,2345", formatCoin(Coin.parseCoin("1.23448")));
setLocale(Locale.US);
assertEquals("1.00", formatCoin(Coin.COIN));
assertEquals("1,012.30", formatCoin(Coin.parseCoin("1012.3")));
// change to mBTC
useMilliBitFormat(true);
assertEquals("1,000.00", formatCoin(Coin.COIN));
assertEquals("1.00", formatCoin(Coin.MILLICOIN));
assertEquals("0.0010", formatCoin(Coin.MICROCOIN));
}
@Test
public void testFormatCoinWithCode() {
useMilliBitFormat(false);
setLocale(Locale.GERMAN);
assertEquals("1,00 BTC", formatCoinWithCode(Coin.COIN));
assertEquals("1,01 BTC", formatCoinWithCode(Coin.parseCoin("1.01")));
assertEquals("1,0120 BTC", formatCoinWithCode(Coin.parseCoin("1.012")));
assertEquals("1.012,30 BTC", formatCoinWithCode(Coin.parseCoin("1012.3")));
assertEquals("1,0120 BTC", formatCoinWithCode(Coin.parseCoin("1.01200")));
assertEquals("1,0123 BTC", formatCoinWithCode(Coin.parseCoin("1.01234")));
assertEquals("1,2345 BTC", formatCoinWithCode(Coin.parseCoin("1.2345")));
assertEquals("1,2346 BTC", formatCoinWithCode(Coin.parseCoin("1.23456")));
assertEquals("1,2346 BTC", formatCoinWithCode(Coin.parseCoin("1.234567")));
assertEquals("1,2345 BTC", formatCoinWithCode(Coin.parseCoin("1.23448")));
setLocale(Locale.US);
assertEquals("1.00 BTC", formatCoinWithCode(Coin.COIN));
assertEquals("1,012.30 BTC", formatCoinWithCode(Coin.parseCoin("1012.3")));
// change to mBTC
useMilliBitFormat(true);
assertEquals("1,000.00 mBTC", formatCoinWithCode(Coin.COIN));
assertEquals("1.00 mBTC", formatCoinWithCode(Coin.MILLICOIN));
assertEquals("0.0010 mBTC", formatCoinWithCode(Coin.MICROCOIN));
}
@Test
public void testParseToBtcWith4Decimals() {
useMilliBitFormat(false);
setLocale(Locale.GERMAN);
assertEquals(Coin.parseCoin("0"), parseToCoinWith4Decimals("0"));
assertEquals(Coin.parseCoin("0"), parseToCoinWith4Decimals(null));
assertEquals(Coin.parseCoin("0"), parseToCoinWith4Decimals("s"));
assertEquals(Coin.parseCoin("0.0012"), parseToCoinWith4Decimals("0,00123"));
assertEquals(Coin.parseCoin("0.0013"), parseToCoinWith4Decimals("0,00125"));
}
/*
@Test @Test
public void testHasBtcValidDecimals() { public void testHasBtcValidDecimals() {
useMilliBitFormat(false);
setLocale(Locale.GERMAN);
assertTrue(hasBtcValidDecimals(null)); assertTrue(hasBtcValidDecimals(null));
assertTrue(hasBtcValidDecimals("0")); assertTrue(hasBtcValidDecimals("0"));
assertTrue(hasBtcValidDecimals("0,0001")); assertTrue(hasBtcValidDecimals("0,0001"));
@ -54,17 +155,20 @@ public class BSFormatterTest {
@Test @Test
public void testParseToFiatWith2Decimals() { public void testParseToFiatWith2Decimals() {
useMilliBitFormat(false);
assertEquals("0", parseToFiatWith2Decimals("0").toPlainString()); setLocale(Locale.GERMAN);
assertEquals("0", parseToFiatWith2Decimals(null).toPlainString()); assertEquals("0", parseToFiatWith2Decimals("0"));
assertEquals("0", parseToFiatWith2Decimals("s").toPlainString()); assertEquals("0", parseToFiatWith2Decimals(null));
assertEquals("0.12", parseToFiatWith2Decimals("0.123").toPlainString()); assertEquals("0", parseToFiatWith2Decimals("s"));
assertEquals("0.13", parseToFiatWith2Decimals("0.125").toPlainString()); assertEquals("0.12", parseToFiatWith2Decimals("0.123"));
assertEquals("0.13", parseToFiatWith2Decimals("0,125").toPlainString()); assertEquals("0.13", parseToFiatWith2Decimals("0.125"));
assertEquals("0.13", parseToFiatWith2Decimals("0,125"));
} }
@Test @Test
public void testHasFiatValidDecimals() { public void testHasFiatValidDecimals() {
useMilliBitFormat(false);
setLocale(Locale.GERMAN);
assertTrue(hasFiatValidDecimals(null)); assertTrue(hasFiatValidDecimals(null));
assertTrue(hasFiatValidDecimals("0")); assertTrue(hasFiatValidDecimals("0"));
assertTrue(hasFiatValidDecimals("0,01")); assertTrue(hasFiatValidDecimals("0,01"));
@ -74,6 +178,6 @@ public class BSFormatterTest {
assertFalse(hasFiatValidDecimals("20000000.0123")); assertFalse(hasFiatValidDecimals("20000000.0123"));
assertFalse(hasFiatValidDecimals("0.012")); assertFalse(hasFiatValidDecimals("0.012"));
assertFalse(hasFiatValidDecimals("0.01222312312312313")); assertFalse(hasFiatValidDecimals("0.01222312312312313"));
} }*/
} }