Remove static methods from BSFormatter

This commit is contained in:
Manfred Karrer 2014-09-26 10:36:51 +02:00
parent 19e71ffad2
commit 1130da6a8f
27 changed files with 324 additions and 312 deletions

View file

@ -12,7 +12,6 @@ public class PresentationModel<T extends UIModel> {
this.model = model; this.model = model;
} }
// TODO Still open question if we enforce a model or not? For small UIs it might be too much overhead.
public PresentationModel() { public PresentationModel() {
} }

View file

@ -44,6 +44,7 @@ public class BalanceTextField extends AnchorPane {
private final Effect fundedEffect = new DropShadow(BlurType.THREE_PASS_BOX, Color.GREEN, 4, 0.0, 0, 0); private final Effect fundedEffect = new DropShadow(BlurType.THREE_PASS_BOX, Color.GREEN, 4, 0.0, 0, 0);
private final Effect notFundedEffect = new DropShadow(BlurType.THREE_PASS_BOX, Color.ORANGERED, 4, 0.0, 0, 0); private final Effect notFundedEffect = new DropShadow(BlurType.THREE_PASS_BOX, Color.ORANGERED, 4, 0.0, 0, 0);
private BSFormatter formatter;
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@ -73,7 +74,8 @@ public class BalanceTextField extends AnchorPane {
getChildren().addAll(balanceTextField, progressIndicator); getChildren().addAll(balanceTextField, progressIndicator);
} }
public void setup(WalletFacade walletFacade, Address address) { public void setup(WalletFacade walletFacade, Address address, BSFormatter formatter) {
this.formatter = formatter;
walletFacade.addAddressConfidenceListener(new AddressConfidenceListener(address) { walletFacade.addAddressConfidenceListener(new AddressConfidenceListener(address) {
@Override @Override
public void onTransactionConfidenceChanged(TransactionConfidence confidence) { public void onTransactionConfidenceChanged(TransactionConfidence confidence) {
@ -127,7 +129,7 @@ public class BalanceTextField extends AnchorPane {
} }
private void updateBalance(Coin balance) { private void updateBalance(Coin balance) {
balanceTextField.setText(BSFormatter.formatCoinWithCode(balance)); balanceTextField.setText(formatter.formatCoinWithCode(balance));
if (balance.isPositive()) if (balance.isPositive())
balanceTextField.setEffect(fundedEffect); balanceTextField.setEffect(fundedEffect);
else else

View file

@ -47,6 +47,7 @@ class MainPM extends PresentationModel<MainModel> {
final StringProperty splashScreenInfoText = new SimpleStringProperty(); final StringProperty splashScreenInfoText = new SimpleStringProperty();
final BooleanProperty networkSyncComplete = new SimpleBooleanProperty(); final BooleanProperty networkSyncComplete = new SimpleBooleanProperty();
final IntegerProperty numPendingTrades = new SimpleIntegerProperty(); final IntegerProperty numPendingTrades = new SimpleIntegerProperty();
private BSFormatter formatter;
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@ -54,8 +55,9 @@ class MainPM extends PresentationModel<MainModel> {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@Inject @Inject
private MainPM(MainModel model) { private MainPM(MainModel model, BSFormatter formatter) {
super(model); super(model);
this.formatter = formatter;
} }
@ -74,7 +76,7 @@ class MainPM extends PresentationModel<MainModel> {
model.networkSyncProgress.addListener((ov, oldValue, newValue) -> { model.networkSyncProgress.addListener((ov, oldValue, newValue) -> {
if ((double) newValue > 0) if ((double) newValue > 0)
splashScreenInfoText.set("Synchronise with network " + BSFormatter.formatToPercent((double) newValue)); splashScreenInfoText.set("Synchronise with network " + formatter.formatToPercent((double) newValue));
else if ((double) newValue == 1) else if ((double) newValue == 1)
splashScreenInfoText.set("Synchronise with network completed."); splashScreenInfoText.set("Synchronise with network completed.");
else else
@ -82,7 +84,7 @@ class MainPM extends PresentationModel<MainModel> {
}); });
model.balance.addListener((ov, oldValue, newValue) -> balance.set(BSFormatter.formatCoinWithCode model.balance.addListener((ov, oldValue, newValue) -> balance.set(formatter.formatCoinWithCode
(newValue))); (newValue)));
model.getBankAccounts().addListener((ListChangeListener<BankAccount>) change -> { model.getBankAccounts().addListener((ListChangeListener<BankAccount>) change -> {

View file

@ -19,6 +19,7 @@ package io.bitsquare.gui.main.account.content.registration;
import io.bitsquare.btc.WalletFacade; import io.bitsquare.btc.WalletFacade;
import io.bitsquare.gui.PresentationModel; import io.bitsquare.gui.PresentationModel;
import io.bitsquare.gui.util.BSFormatter;
import io.bitsquare.locale.BSResources; import io.bitsquare.locale.BSResources;
import com.google.bitcoin.core.Address; import com.google.bitcoin.core.Address;
@ -36,7 +37,6 @@ import javafx.beans.property.StringProperty;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import static io.bitsquare.gui.util.BSFormatter.formatCoinWithCode;
class RegistrationPM extends PresentationModel<RegistrationModel> { class RegistrationPM extends PresentationModel<RegistrationModel> {
private static final Logger log = LoggerFactory.getLogger(RegistrationPM.class); private static final Logger log = LoggerFactory.getLogger(RegistrationPM.class);
@ -47,6 +47,7 @@ class RegistrationPM extends PresentationModel<RegistrationModel> {
// That is needed for the addressTextField // That is needed for the addressTextField
final ObjectProperty<Address> address = new SimpleObjectProperty<>(); final ObjectProperty<Address> address = new SimpleObjectProperty<>();
private BSFormatter formatter;
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@ -54,8 +55,9 @@ class RegistrationPM extends PresentationModel<RegistrationModel> {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@Inject @Inject
private RegistrationPM(RegistrationModel model) { private RegistrationPM(RegistrationModel model, BSFormatter formatter) {
super(model); super(model);
this.formatter = formatter;
} }
@ -124,6 +126,10 @@ class RegistrationPM extends PresentationModel<RegistrationModel> {
return model.getWalletFacade(); return model.getWalletFacade();
} }
BSFormatter getFormatter() {
return formatter;
}
Coin getFeeAsCoin() { Coin getFeeAsCoin() {
return model.getFeeAsCoin(); return model.getFeeAsCoin();
} }
@ -137,7 +143,7 @@ class RegistrationPM extends PresentationModel<RegistrationModel> {
} }
String getFeeAsString() { String getFeeAsString() {
return formatCoinWithCode(model.getFeeAsCoin()); return formatter.formatCoinWithCode(model.getFeeAsCoin());
} }
String getTransactionId() { String getTransactionId() {
@ -153,4 +159,5 @@ class RegistrationPM extends PresentationModel<RegistrationModel> {
isPayButtonDisabled.set(!(model.isWalletFunded.get())); isPayButtonDisabled.set(!(model.isWalletFunded.get()));
} }
} }

View file

@ -88,7 +88,8 @@ public class RegistrationViewCB extends CachedViewCB<RegistrationPM> implements
// TODO find better solution // TODO find better solution
addressTextField.setOverlayManager(overlayManager); addressTextField.setOverlayManager(overlayManager);
balanceTextField.setup(presentationModel.getWalletFacade(), presentationModel.address.get()); balanceTextField.setup(presentationModel.getWalletFacade(), presentationModel.address.get(),
presentationModel.getFormatter());
payButton.disableProperty().bind(presentationModel.isPayButtonDisabled); payButton.disableProperty().bind(presentationModel.isPayButtonDisabled);

View file

@ -32,6 +32,7 @@ class SeedWordsPM extends PresentationModel<SeedWordsModel> {
private static final Logger log = LoggerFactory.getLogger(SeedWordsPM.class); private static final Logger log = LoggerFactory.getLogger(SeedWordsPM.class);
final StringProperty seedWords = new SimpleStringProperty(); final StringProperty seedWords = new SimpleStringProperty();
private BSFormatter formatter;
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@ -39,8 +40,9 @@ class SeedWordsPM extends PresentationModel<SeedWordsModel> {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@Inject @Inject
private SeedWordsPM(SeedWordsModel model) { private SeedWordsPM(SeedWordsModel model, BSFormatter formatter) {
super(model); super(model);
this.formatter = formatter;
} }
@ -54,7 +56,7 @@ class SeedWordsPM extends PresentationModel<SeedWordsModel> {
super.initialize(); super.initialize();
if (model.getMnemonicCode() != null) if (model.getMnemonicCode() != null)
seedWords.set(BSFormatter.mnemonicCodeToString(model.getMnemonicCode())); seedWords.set(formatter.mnemonicCodeToString(model.getMnemonicCode()));
} }
@SuppressWarnings("EmptyMethod") @SuppressWarnings("EmptyMethod")

View file

@ -40,6 +40,7 @@ public class ArbitratorProfileController extends CachedViewController {
private final Settings settings; private final Settings settings;
private final Persistence persistence; private final Persistence persistence;
private BSFormatter formatter;
private Arbitrator arbitrator; private Arbitrator arbitrator;
@ -55,12 +56,13 @@ public class ArbitratorProfileController extends CachedViewController {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@Inject @Inject
public ArbitratorProfileController(Settings settings, Persistence persistence) { public ArbitratorProfileController(Settings settings, Persistence persistence, BSFormatter formatter) {
this.settings = settings; this.settings = settings;
this.persistence = persistence; this.persistence = persistence;
// Settings persistedSettings = (Settings) storage.read(settings.getClass().getName()); // Settings persistedSettings = (Settings) storage.read(settings.getClass().getName());
// settings.applyPersistedSettings(persistedSettings); // settings.applyPersistedSettings(persistedSettings);
this.formatter = formatter;
} }
@ -125,16 +127,16 @@ public class ArbitratorProfileController extends CachedViewController {
nameLabel.setText(name); nameLabel.setText(name);
nameTextField.setText(arbitrator.getName()); nameTextField.setText(arbitrator.getName());
languagesTextField.setText(BSFormatter.languageLocalesToString(arbitrator.getLanguages())); languagesTextField.setText(formatter.languageLocalesToString(arbitrator.getLanguages()));
reputationTextField.setText(arbitrator.getReputation().toString()); reputationTextField.setText(arbitrator.getReputation().toString());
maxTradeVolumeTextField.setText(String.valueOf(arbitrator.getMaxTradeVolume()) + " BTC"); maxTradeVolumeTextField.setText(String.valueOf(arbitrator.getMaxTradeVolume()) + " BTC");
passiveServiceFeeTextField.setText(String.valueOf(arbitrator.getPassiveServiceFee()) + " % (Min. " + passiveServiceFeeTextField.setText(String.valueOf(arbitrator.getPassiveServiceFee()) + " % (Min. " +
String.valueOf(arbitrator.getMinPassiveServiceFee()) + " BTC)"); String.valueOf(arbitrator.getMinPassiveServiceFee()) + " BTC)");
arbitrationFeeTextField.setText(String.valueOf(arbitrator.getArbitrationFee()) + " % (Min. " + String arbitrationFeeTextField.setText(String.valueOf(arbitrator.getArbitrationFee()) + " % (Min. " + String
.valueOf(arbitrator.getMinArbitrationFee()) + " BTC)"); .valueOf(arbitrator.getMinArbitrationFee()) + " BTC)");
methodsTextField.setText(BSFormatter.arbitrationMethodsToString(arbitrator.getArbitrationMethods())); methodsTextField.setText(formatter.arbitrationMethodsToString(arbitrator.getArbitrationMethods()));
idVerificationsTextField.setText( idVerificationsTextField.setText(
BSFormatter.arbitrationIDVerificationsToString(arbitrator.getIdVerifications())); formatter.arbitrationIDVerificationsToString(arbitrator.getIdVerifications()));
webPageTextField.setText(arbitrator.getWebUrl()); webPageTextField.setText(arbitrator.getWebUrl());
descriptionTextArea.setText(arbitrator.getDescription()); descriptionTextArea.setText(arbitrator.getDescription());
} }

View file

@ -71,6 +71,7 @@ public class ArbitratorRegistrationController extends CachedViewController {
private final WalletFacade walletFacade; private final WalletFacade walletFacade;
private final MessageFacade messageFacade; private final MessageFacade messageFacade;
private final User user; private final User user;
private BSFormatter formatter;
private Arbitrator arbitrator = new Arbitrator(); private Arbitrator arbitrator = new Arbitrator();
private ArbitratorProfileController arbitratorProfileController; private ArbitratorProfileController arbitratorProfileController;
private boolean isEditMode; private boolean isEditMode;
@ -104,11 +105,12 @@ public class ArbitratorRegistrationController extends CachedViewController {
@Inject @Inject
private ArbitratorRegistrationController(Persistence persistence, WalletFacade walletFacade, private ArbitratorRegistrationController(Persistence persistence, WalletFacade walletFacade,
MessageFacade messageFacade, User user) { MessageFacade messageFacade, User user, BSFormatter formatter) {
this.persistence = persistence; this.persistence = persistence;
this.walletFacade = walletFacade; this.walletFacade = walletFacade;
this.messageFacade = messageFacade; this.messageFacade = messageFacade;
this.user = user; this.user = user;
this.formatter = formatter;
} }
@ -129,7 +131,7 @@ public class ArbitratorRegistrationController extends CachedViewController {
} }
else { else {
languageList.add(LanguageUtil.getDefaultLanguageLocale()); languageList.add(LanguageUtil.getDefaultLanguageLocale());
languagesTextField.setText(BSFormatter.languageLocalesToString(languageList)); languagesTextField.setText(formatter.languageLocalesToString(languageList));
} }
languageComboBox.setItems(FXCollections.observableArrayList(LanguageUtil.getAllLanguageLocales())); languageComboBox.setItems(FXCollections.observableArrayList(LanguageUtil.getAllLanguageLocales()));
@ -274,7 +276,7 @@ public class ArbitratorRegistrationController extends CachedViewController {
Locale item = languageComboBox.getSelectionModel().getSelectedItem(); Locale item = languageComboBox.getSelectionModel().getSelectedItem();
if (!languageList.contains(item) && item != null) { if (!languageList.contains(item) && item != null) {
languageList.add(item); languageList.add(item);
languagesTextField.setText(BSFormatter.languageLocalesToString(languageList)); languagesTextField.setText(formatter.languageLocalesToString(languageList));
languageComboBox.getSelectionModel().clearSelection(); languageComboBox.getSelectionModel().clearSelection();
} }
} }
@ -290,7 +292,7 @@ public class ArbitratorRegistrationController extends CachedViewController {
Arbitrator.METHOD item = methodsComboBox.getSelectionModel().getSelectedItem(); Arbitrator.METHOD item = methodsComboBox.getSelectionModel().getSelectedItem();
if (!methodList.contains(item) && item != null) { if (!methodList.contains(item) && item != null) {
methodList.add(item); methodList.add(item);
methodsTextField.setText(BSFormatter.arbitrationMethodsToString(methodList)); methodsTextField.setText(formatter.arbitrationMethodsToString(methodList));
methodsComboBox.getSelectionModel().clearSelection(); methodsComboBox.getSelectionModel().clearSelection();
} }
} }
@ -309,7 +311,7 @@ public class ArbitratorRegistrationController extends CachedViewController {
if (!idVerificationList.contains(idVerification)) { if (!idVerificationList.contains(idVerification)) {
idVerificationList.add(idVerification); idVerificationList.add(idVerification);
idVerificationsTextField.setText( idVerificationsTextField.setText(
BSFormatter.arbitrationIDVerificationsToString(idVerificationList)); formatter.arbitrationIDVerificationsToString(idVerificationList));
} }
} }
@ -429,15 +431,15 @@ public class ArbitratorRegistrationController extends CachedViewController {
nameTextField.setText(arbitrator.getName()); nameTextField.setText(arbitrator.getName());
idTypeTextField.setText(BSResources.get(arbitrator.getIdType().toString())); idTypeTextField.setText(BSResources.get(arbitrator.getIdType().toString()));
languagesTextField.setText(BSFormatter.languageLocalesToString(arbitrator.getLanguages())); languagesTextField.setText(formatter.languageLocalesToString(arbitrator.getLanguages()));
maxTradeVolumeTextField.setText(String.valueOf(arbitrator.getMaxTradeVolume())); maxTradeVolumeTextField.setText(String.valueOf(arbitrator.getMaxTradeVolume()));
passiveServiceFeeTextField.setText(String.valueOf(arbitrator.getPassiveServiceFee())); passiveServiceFeeTextField.setText(String.valueOf(arbitrator.getPassiveServiceFee()));
minPassiveServiceFeeTextField.setText(String.valueOf(arbitrator.getMinPassiveServiceFee())); minPassiveServiceFeeTextField.setText(String.valueOf(arbitrator.getMinPassiveServiceFee()));
arbitrationFeeTextField.setText(String.valueOf(arbitrator.getArbitrationFee())); arbitrationFeeTextField.setText(String.valueOf(arbitrator.getArbitrationFee()));
minArbitrationFeeTextField.setText(String.valueOf(arbitrator.getMinArbitrationFee())); minArbitrationFeeTextField.setText(String.valueOf(arbitrator.getMinArbitrationFee()));
methodsTextField.setText(BSFormatter.arbitrationMethodsToString(arbitrator.getArbitrationMethods())); methodsTextField.setText(formatter.arbitrationMethodsToString(arbitrator.getArbitrationMethods()));
idVerificationsTextField.setText( idVerificationsTextField.setText(
BSFormatter.arbitrationIDVerificationsToString(arbitrator.getIdVerifications())); formatter.arbitrationIDVerificationsToString(arbitrator.getIdVerifications()));
webPageTextField.setText(arbitrator.getWebUrl()); webPageTextField.setText(arbitrator.getWebUrl());
descriptionTextArea.setText(arbitrator.getDescription()); descriptionTextArea.setText(arbitrator.getDescription());
@ -454,11 +456,11 @@ public class ArbitratorRegistrationController extends CachedViewController {
String messagePubKeyAsHex = DSAKeyUtil.getHexStringFromPublicKey(user.getMessagePublicKey()); String messagePubKeyAsHex = DSAKeyUtil.getHexStringFromPublicKey(user.getMessagePublicKey());
String name = nameTextField.getText(); String name = nameTextField.getText();
double maxTradeVolume = BSFormatter.parseToDouble(maxTradeVolumeTextField.getText()); double maxTradeVolume = formatter.parseToDouble(maxTradeVolumeTextField.getText());
double passiveServiceFee = BSFormatter.parseToDouble(passiveServiceFeeTextField.getText()); double passiveServiceFee = formatter.parseToDouble(passiveServiceFeeTextField.getText());
double minPassiveServiceFee = BSFormatter.parseToDouble(minPassiveServiceFeeTextField.getText()); double minPassiveServiceFee = formatter.parseToDouble(minPassiveServiceFeeTextField.getText());
double arbitrationFee = BSFormatter.parseToDouble(arbitrationFeeTextField.getText()); double arbitrationFee = formatter.parseToDouble(arbitrationFeeTextField.getText());
double minArbitrationFee = BSFormatter.parseToDouble(minArbitrationFeeTextField.getText()); double minArbitrationFee = formatter.parseToDouble(minArbitrationFeeTextField.getText());
String webUrl = webPageTextField.getText(); String webUrl = webPageTextField.getText();
String description = descriptionTextArea.getText(); String description = descriptionTextArea.getText();

View file

@ -19,6 +19,7 @@ package io.bitsquare.gui.main.funds.transactions;
import io.bitsquare.btc.WalletFacade; import io.bitsquare.btc.WalletFacade;
import io.bitsquare.gui.CachedViewController; import io.bitsquare.gui.CachedViewController;
import io.bitsquare.gui.util.BSFormatter;
import com.google.bitcoin.core.Transaction; import com.google.bitcoin.core.Transaction;
@ -44,6 +45,7 @@ public class TransactionsController extends CachedViewController {
private static final Logger log = LoggerFactory.getLogger(TransactionsController.class); private static final Logger log = LoggerFactory.getLogger(TransactionsController.class);
private final WalletFacade walletFacade; private final WalletFacade walletFacade;
private BSFormatter formatter;
private ObservableList<TransactionsListItem> transactionsListItems; private ObservableList<TransactionsListItem> transactionsListItems;
@FXML TableView<TransactionsListItem> tableView; @FXML TableView<TransactionsListItem> tableView;
@ -56,8 +58,9 @@ public class TransactionsController extends CachedViewController {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@Inject @Inject
private TransactionsController(WalletFacade walletFacade) { private TransactionsController(WalletFacade walletFacade, BSFormatter formatter) {
this.walletFacade = walletFacade; this.walletFacade = walletFacade;
this.formatter = formatter;
} }
@ -90,7 +93,7 @@ public class TransactionsController extends CachedViewController {
List<Transaction> transactions = walletFacade.getWallet().getRecentTransactions(10000, true); List<Transaction> transactions = walletFacade.getWallet().getRecentTransactions(10000, true);
transactionsListItems = FXCollections.observableArrayList(); transactionsListItems = FXCollections.observableArrayList();
transactionsListItems.addAll(transactions.stream().map(transaction -> transactionsListItems.addAll(transactions.stream().map(transaction ->
new TransactionsListItem(transaction, walletFacade)).collect(Collectors.toList())); new TransactionsListItem(transaction, walletFacade, formatter)).collect(Collectors.toList()));
tableView.setItems(transactionsListItems); tableView.setItems(transactionsListItems);
} }

View file

@ -49,14 +49,14 @@ public class TransactionsListItem {
private String addressString; private String addressString;
private AddressConfidenceListener confidenceListener; private AddressConfidenceListener confidenceListener;
public TransactionsListItem(Transaction transaction, WalletFacade walletFacade) { public TransactionsListItem(Transaction transaction, WalletFacade walletFacade, BSFormatter formatter) {
this.walletFacade = walletFacade; this.walletFacade = walletFacade;
Coin valueSentToMe = transaction.getValueSentToMe(walletFacade.getWallet()); Coin valueSentToMe = transaction.getValueSentToMe(walletFacade.getWallet());
Coin valueSentFromMe = transaction.getValueSentFromMe(walletFacade.getWallet()); Coin valueSentFromMe = transaction.getValueSentFromMe(walletFacade.getWallet());
Address address = null; Address address = null;
if (valueSentToMe.isZero()) { if (valueSentToMe.isZero()) {
amount.set("-" + BSFormatter.formatCoin(valueSentFromMe)); amount.set("-" + formatter.formatCoin(valueSentFromMe));
for (TransactionOutput transactionOutput : transaction.getOutputs()) { for (TransactionOutput transactionOutput : transaction.getOutputs()) {
if (!transactionOutput.isMine(walletFacade.getWallet())) { if (!transactionOutput.isMine(walletFacade.getWallet())) {
@ -75,7 +75,7 @@ public class TransactionsListItem {
} }
} }
else if (valueSentFromMe.isZero()) { else if (valueSentFromMe.isZero()) {
amount.set(BSFormatter.formatCoin(valueSentToMe)); amount.set(formatter.formatCoin(valueSentToMe));
type.set("Received with"); type.set("Received with");
for (TransactionOutput transactionOutput : transaction.getOutputs()) { for (TransactionOutput transactionOutput : transaction.getOutputs()) {
@ -93,7 +93,7 @@ public class TransactionsListItem {
} }
} }
else { else {
amount.set(BSFormatter.formatCoin(valueSentToMe.subtract(valueSentFromMe))); amount.set(formatter.formatCoin(valueSentToMe.subtract(valueSentFromMe)));
boolean outgoing = false; boolean outgoing = false;
for (TransactionOutput transactionOutput : transaction.getOutputs()) { for (TransactionOutput transactionOutput : transaction.getOutputs()) {
if (!transactionOutput.isMine(walletFacade.getWallet())) { if (!transactionOutput.isMine(walletFacade.getWallet())) {
@ -119,7 +119,7 @@ public class TransactionsListItem {
} }
} }
date.set(BSFormatter.formatDateTime(transaction.getUpdateTime())); date.set(formatter.formatDateTime(transaction.getUpdateTime()));
// confidence // confidence
progressIndicator = new ConfidenceProgressIndicator(); progressIndicator = new ConfidenceProgressIndicator();

View file

@ -64,6 +64,7 @@ public class WithdrawalController extends CachedViewController {
private final WalletFacade walletFacade; private final WalletFacade walletFacade;
private BSFormatter formatter;
private ObservableList<WithdrawalListItem> addressList; private ObservableList<WithdrawalListItem> addressList;
@FXML TableView<WithdrawalListItem> tableView; @FXML TableView<WithdrawalListItem> tableView;
@ -78,8 +79,9 @@ public class WithdrawalController extends CachedViewController {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@Inject @Inject
private WithdrawalController(WalletFacade walletFacade) { private WithdrawalController(WalletFacade walletFacade, BSFormatter formatter) {
this.walletFacade = walletFacade; this.walletFacade = walletFacade;
this.formatter = formatter;
} }
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@ -130,7 +132,7 @@ public class WithdrawalController extends CachedViewController {
List<AddressEntry> addressEntryList = walletFacade.getAddressEntryList(); List<AddressEntry> addressEntryList = walletFacade.getAddressEntryList();
addressList = FXCollections.observableArrayList(); addressList = FXCollections.observableArrayList();
addressList.addAll(addressEntryList.stream().map(anAddressEntryList -> addressList.addAll(addressEntryList.stream().map(anAddressEntryList ->
new WithdrawalListItem(anAddressEntryList, walletFacade)).collect(Collectors.toList())); new WithdrawalListItem(anAddressEntryList, walletFacade, formatter)).collect(Collectors.toList()));
tableView.setItems(addressList); tableView.setItems(addressList);
} }
@ -142,7 +144,7 @@ public class WithdrawalController extends CachedViewController {
@FXML @FXML
public void onWithdraw() { public void onWithdraw() {
Coin amount = BSFormatter.parseToCoin(amountTextField.getText()); Coin amount = formatter.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
@ -163,9 +165,9 @@ public class WithdrawalController extends CachedViewController {
"Your withdrawal request:\n\n" + "Amount: " + amountTextField.getText() + " BTC\n" + "Sending" + "Your withdrawal request:\n\n" + "Amount: " + amountTextField.getText() + " BTC\n" + "Sending" +
" address: " + withdrawFromTextField.getText() + "\n" + "Receiving address: " + " address: " + withdrawFromTextField.getText() + "\n" + "Receiving address: " +
withdrawToTextField.getText() + "\n" + "Transaction fee: " + withdrawToTextField.getText() + "\n" + "Transaction fee: " +
BSFormatter.formatCoinWithCode(FeePolicy.TX_FEE) + "\n" + formatter.formatCoinWithCode(FeePolicy.TX_FEE) + "\n" +
"You receive in total: " + "You receive in total: " +
BSFormatter.formatCoinWithCode(amount.subtract(FeePolicy.TX_FEE)) + " BTC\n\n" + formatter.formatCoinWithCode(amount.subtract(FeePolicy.TX_FEE)) + " BTC\n\n" +
"Are you sure you withdraw that amount?"); "Are you sure you withdraw that amount?");
if (response == Dialog.Actions.OK) { if (response == Dialog.Actions.OK) {
try { try {

View file

@ -43,6 +43,7 @@ public class WithdrawalListItem {
private final AddressEntry addressEntry; private final AddressEntry addressEntry;
private final WalletFacade walletFacade; private final WalletFacade walletFacade;
private BSFormatter formatter;
private final AddressConfidenceListener confidenceListener; private final AddressConfidenceListener confidenceListener;
private final ConfidenceProgressIndicator progressIndicator; private final ConfidenceProgressIndicator progressIndicator;
@ -51,9 +52,10 @@ public class WithdrawalListItem {
private Coin balance; private Coin balance;
public WithdrawalListItem(AddressEntry addressEntry, WalletFacade walletFacade) { public WithdrawalListItem(AddressEntry addressEntry, WalletFacade walletFacade, BSFormatter formatter) {
this.addressEntry = addressEntry; this.addressEntry = addressEntry;
this.walletFacade = walletFacade; this.walletFacade = walletFacade;
this.formatter = formatter;
this.addressString.set(getAddress().toString()); this.addressString.set(getAddress().toString());
// confidence // confidence
@ -94,7 +96,7 @@ public class WithdrawalListItem {
private void updateBalance(Coin balance) { private void updateBalance(Coin balance) {
this.balance = balance; this.balance = balance;
if (balance != null) { if (balance != null) {
balanceLabel.setText(BSFormatter.formatCoin(balance)); balanceLabel.setText(formatter.formatCoin(balance));
} }
} }

View file

@ -84,19 +84,19 @@ class ClosedTradesPM extends PresentationModel<ClosedTradesModel> {
} }
String getAmount(ClosedTradesListItem item) { String getAmount(ClosedTradesListItem item) {
return (item != null) ? BSFormatter.formatAmountWithMinAmount(item.getTrade().getOffer()) : ""; return (item != null) ? formatter.formatAmountWithMinAmount(item.getTrade().getOffer()) : "";
} }
String getPrice(ClosedTradesListItem item) { String getPrice(ClosedTradesListItem item) {
return (item != null) ? BSFormatter.formatFiat(item.getTrade().getOffer().getPrice()) : ""; return (item != null) ? formatter.formatFiat(item.getTrade().getOffer().getPrice()) : "";
} }
String getVolume(ClosedTradesListItem item) { String getVolume(ClosedTradesListItem item) {
return (item != null) ? BSFormatter.formatVolumeWithMinVolume(item.getTrade().getOffer()) : ""; return (item != null) ? formatter.formatVolumeWithMinVolume(item.getTrade().getOffer()) : "";
} }
String getDirectionLabel(ClosedTradesListItem item) { String getDirectionLabel(ClosedTradesListItem item) {
return (item != null) ? BSFormatter.formatDirection(item.getTrade().getOffer().getMirroredDirection()) : ""; return (item != null) ? formatter.formatDirection(item.getTrade().getOffer().getMirroredDirection()) : "";
} }
String getDate(ClosedTradesListItem item) { String getDate(ClosedTradesListItem item) {

View file

@ -93,19 +93,19 @@ class OffersPM extends PresentationModel<OffersModel> {
} }
String getAmount(OfferListItem item) { String getAmount(OfferListItem item) {
return (item != null) ? BSFormatter.formatAmountWithMinAmount(item.getOffer()) : ""; return (item != null) ? formatter.formatAmountWithMinAmount(item.getOffer()) : "";
} }
String getPrice(OfferListItem item) { String getPrice(OfferListItem item) {
return (item != null) ? BSFormatter.formatFiat(item.getOffer().getPrice()) : ""; return (item != null) ? formatter.formatFiat(item.getOffer().getPrice()) : "";
} }
String getVolume(OfferListItem item) { String getVolume(OfferListItem item) {
return (item != null) ? BSFormatter.formatVolumeWithMinVolume(item.getOffer()) : ""; return (item != null) ? formatter.formatVolumeWithMinVolume(item.getOffer()) : "";
} }
String getDirectionLabel(OfferListItem item) { String getDirectionLabel(OfferListItem item) {
return (item != null) ? BSFormatter.formatDirection(item.getOffer().getMirroredDirection()) : ""; return (item != null) ? formatter.formatDirection(item.getOffer().getMirroredDirection()) : "";
} }
String getDate(OfferListItem item) { String getDate(OfferListItem item) {

View file

@ -154,19 +154,19 @@ public class PendingTradesPM extends PresentationModel<PendingTradesModel> {
} }
String getAmount(PendingTradesListItem item) { String getAmount(PendingTradesListItem item) {
return (item != null) ? BSFormatter.formatAmountWithMinAmount(item.getTrade().getOffer()) : ""; return (item != null) ? formatter.formatAmountWithMinAmount(item.getTrade().getOffer()) : "";
} }
String getPrice(PendingTradesListItem item) { String getPrice(PendingTradesListItem item) {
return (item != null) ? BSFormatter.formatFiat(item.getTrade().getOffer().getPrice()) : ""; return (item != null) ? formatter.formatFiat(item.getTrade().getOffer().getPrice()) : "";
} }
String getVolume(PendingTradesListItem item) { String getVolume(PendingTradesListItem item) {
return (item != null) ? BSFormatter.formatVolumeWithMinVolume(item.getTrade().getOffer()) : ""; return (item != null) ? formatter.formatVolumeWithMinVolume(item.getTrade().getOffer()) : "";
} }
String getDirectionLabel(PendingTradesListItem item) { String getDirectionLabel(PendingTradesListItem item) {
return (item != null) ? BSFormatter.formatDirection(item.getTrade().getOffer().getMirroredDirection()) : ""; return (item != null) ? formatter.formatDirection(item.getTrade().getOffer().getMirroredDirection()) : "";
} }
String getDate(PendingTradesListItem item) { String getDate(PendingTradesListItem item) {

View file

@ -24,6 +24,7 @@ import io.bitsquare.btc.FeePolicy;
import io.bitsquare.btc.WalletFacade; import io.bitsquare.btc.WalletFacade;
import io.bitsquare.btc.listeners.BalanceListener; import io.bitsquare.btc.listeners.BalanceListener;
import io.bitsquare.gui.UIModel; import io.bitsquare.gui.UIModel;
import io.bitsquare.gui.util.BSFormatter;
import io.bitsquare.locale.Country; import io.bitsquare.locale.Country;
import io.bitsquare.settings.Settings; import io.bitsquare.settings.Settings;
import io.bitsquare.trade.Direction; import io.bitsquare.trade.Direction;
@ -57,7 +58,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static io.bitsquare.gui.util.BSFormatter.reduceTo4Decimals;
/** /**
* Domain for that UI element. * Domain for that UI element.
@ -71,6 +71,7 @@ class CreateOfferModel extends UIModel {
private final WalletFacade walletFacade; private final WalletFacade walletFacade;
private final Settings settings; private final Settings settings;
private final User user; private final User user;
private BSFormatter formatter;
private final String offerId; private final String offerId;
@ -111,11 +112,13 @@ class CreateOfferModel extends UIModel {
// non private for testing // non private for testing
@Inject @Inject
public CreateOfferModel(TradeManager tradeManager, WalletFacade walletFacade, Settings settings, User user) { public CreateOfferModel(TradeManager tradeManager, WalletFacade walletFacade, Settings settings, User user,
BSFormatter formatter) {
this.tradeManager = tradeManager; this.tradeManager = tradeManager;
this.walletFacade = walletFacade; this.walletFacade = walletFacade;
this.settings = settings; this.settings = settings;
this.user = user; this.user = user;
this.formatter = formatter;
offerId = UUID.randomUUID().toString(); offerId = UUID.randomUUID().toString();
} }
@ -228,7 +231,8 @@ class CreateOfferModel extends UIModel {
!volumeAsFiat.get().isZero() && !volumeAsFiat.get().isZero() &&
!priceAsFiat.get().isZero()) { !priceAsFiat.get().isZero()) {
// 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
amountAsCoin.set(reduceTo4Decimals(new ExchangeRate(priceAsFiat.get()).fiatToCoin(volumeAsFiat.get()))); amountAsCoin.set(formatter.reduceTo4Decimals(new ExchangeRate(priceAsFiat.get()).fiatToCoin
(volumeAsFiat.get())));
calculateTotalToPay(); calculateTotalToPay();
calculateCollateral(); calculateCollateral();

View file

@ -44,13 +44,13 @@ import javafx.beans.property.StringProperty;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import static io.bitsquare.gui.util.BSFormatter.*;
import static javafx.beans.binding.Bindings.createStringBinding; import static javafx.beans.binding.Bindings.createStringBinding;
class CreateOfferPM extends PresentationModel<CreateOfferModel> { class CreateOfferPM extends PresentationModel<CreateOfferModel> {
private static final Logger log = LoggerFactory.getLogger(CreateOfferPM.class); private static final Logger log = LoggerFactory.getLogger(CreateOfferPM.class);
private final BtcValidator btcValidator; private final BtcValidator btcValidator;
private BSFormatter formatter;
private final FiatValidator fiatValidator; private final FiatValidator fiatValidator;
final StringProperty amount = new SimpleStringProperty(); final StringProperty amount = new SimpleStringProperty();
@ -100,11 +100,13 @@ class CreateOfferPM extends PresentationModel<CreateOfferModel> {
// non private for testing // non private for testing
@Inject @Inject
CreateOfferPM(CreateOfferModel model, FiatValidator fiatValidator, BtcValidator btcValidator) { CreateOfferPM(CreateOfferModel model, FiatValidator fiatValidator, BtcValidator btcValidator,
BSFormatter formatter) {
super(model); super(model);
this.fiatValidator = fiatValidator; this.fiatValidator = fiatValidator;
this.btcValidator = btcValidator; this.btcValidator = btcValidator;
this.formatter = formatter;
} }
@ -169,7 +171,7 @@ class CreateOfferPM extends PresentationModel<CreateOfferModel> {
// apply only if valid // apply only if valid
boolean priceValid = false; boolean priceValid = false;
if (price != null && isBtcInputValid(price.toPlainString()).isValid) { if (price != null && isBtcInputValid(price.toPlainString()).isValid) {
model.priceAsFiat.set(parseToFiatWith2Decimals(price.toPlainString())); model.priceAsFiat.set(formatter.parseToFiatWith2Decimals(price.toPlainString()));
priceValid = true; priceValid = true;
} }
@ -206,11 +208,11 @@ class CreateOfferPM extends PresentationModel<CreateOfferModel> {
InputValidator.ValidationResult result = isBtcInputValid(amount.get()); InputValidator.ValidationResult result = isBtcInputValid(amount.get());
amountValidationResult.set(result); amountValidationResult.set(result);
if (result.isValid) { if (result.isValid) {
showWarningInvalidBtcDecimalPlaces.set(!hasBtcValidDecimals(userInput)); showWarningInvalidBtcDecimalPlaces.set(!formatter.hasBtcValidDecimals(userInput));
// only allow max 4 decimal places for btc values // only allow max 4 decimal places for btc values
setAmountToModel(); setAmountToModel();
// reformat input // reformat input
amount.set(formatCoin(model.amountAsCoin.get())); amount.set(formatter.formatCoin(model.amountAsCoin.get()));
calculateVolume(); calculateVolume();
@ -233,9 +235,9 @@ class CreateOfferPM extends PresentationModel<CreateOfferModel> {
InputValidator.ValidationResult result = isBtcInputValid(minAmount.get()); InputValidator.ValidationResult result = isBtcInputValid(minAmount.get());
minAmountValidationResult.set(result); minAmountValidationResult.set(result);
if (result.isValid) { if (result.isValid) {
showWarningInvalidBtcDecimalPlaces.set(!hasBtcValidDecimals(userInput)); showWarningInvalidBtcDecimalPlaces.set(!formatter.hasBtcValidDecimals(userInput));
setMinAmountToModel(); setMinAmountToModel();
minAmount.set(formatCoin(model.minAmountAsCoin.get())); minAmount.set(formatter.formatCoin(model.minAmountAsCoin.get()));
if (!model.isMinAmountLessOrEqualAmount()) { if (!model.isMinAmountLessOrEqualAmount()) {
minAmountValidationResult.set(new InputValidator.ValidationResult(false, minAmountValidationResult.set(new InputValidator.ValidationResult(false,
@ -256,9 +258,9 @@ class CreateOfferPM extends PresentationModel<CreateOfferModel> {
boolean isValid = result.isValid; boolean isValid = result.isValid;
priceValidationResult.set(result); priceValidationResult.set(result);
if (isValid) { if (isValid) {
showWarningInvalidFiatDecimalPlaces.set(!hasFiatValidDecimals(userInput)); showWarningInvalidFiatDecimalPlaces.set(!formatter.hasFiatValidDecimals(userInput));
setPriceToModel(); setPriceToModel();
price.set(formatFiat(model.priceAsFiat.get())); price.set(formatter.formatFiat(model.priceAsFiat.get()));
calculateVolume(); calculateVolume();
} }
@ -270,15 +272,16 @@ class CreateOfferPM extends PresentationModel<CreateOfferModel> {
InputValidator.ValidationResult result = isBtcInputValid(volume.get()); InputValidator.ValidationResult result = isBtcInputValid(volume.get());
volumeValidationResult.set(result); volumeValidationResult.set(result);
if (result.isValid) { if (result.isValid) {
showWarningInvalidFiatDecimalPlaces.set(!hasFiatValidDecimals(userInput)); showWarningInvalidFiatDecimalPlaces.set(!formatter.hasFiatValidDecimals(userInput));
setVolumeToModel(); setVolumeToModel();
volume.set(formatFiat(model.volumeAsFiat.get())); volume.set(formatter.formatFiat(model.volumeAsFiat.get()));
calculateAmount(); calculateAmount();
// must be placed after calculateAmount (btc value has been adjusted in case the calculation leads to // must be placed after calculateAmount (btc value has been adjusted in case the calculation leads to
// invalid decimal places for the amount value // invalid decimal places for the amount value
showWarningAdjustedVolume.set(!formatFiat(parseToFiatWith2Decimals(userInput)).equals(volume showWarningAdjustedVolume.set(!formatter.formatFiat(formatter.parseToFiatWith2Decimals(userInput))
.equals(volume
.get())); .get()));
} }
} }
@ -293,6 +296,9 @@ class CreateOfferPM extends PresentationModel<CreateOfferModel> {
return model.getWalletFacade(); return model.getWalletFacade();
} }
BSFormatter getFormatter() {
return formatter;
}
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// Private // Private
@ -342,10 +348,10 @@ class CreateOfferPM extends PresentationModel<CreateOfferModel> {
}); });
// Binding with Bindings.createObjectBinding does not work because of bi-directional binding // Binding with Bindings.createObjectBinding does not work because of bi-directional binding
model.amountAsCoin.addListener((ov, oldValue, newValue) -> amount.set(formatCoin(newValue))); model.amountAsCoin.addListener((ov, oldValue, newValue) -> amount.set(formatter.formatCoin(newValue)));
model.minAmountAsCoin.addListener((ov, oldValue, newValue) -> minAmount.set(formatCoin(newValue))); model.minAmountAsCoin.addListener((ov, oldValue, newValue) -> minAmount.set(formatter.formatCoin(newValue)));
model.priceAsFiat.addListener((ov, oldValue, newValue) -> price.set(formatFiat(newValue))); model.priceAsFiat.addListener((ov, oldValue, newValue) -> price.set(formatter.formatFiat(newValue)));
model.volumeAsFiat.addListener((ov, oldValue, newValue) -> volume.set(formatFiat(newValue))); model.volumeAsFiat.addListener((ov, oldValue, newValue) -> volume.set(formatter.formatFiat(newValue)));
model.requestPlaceOfferErrorMessage.addListener((ov, oldValue, newValue) -> { model.requestPlaceOfferErrorMessage.addListener((ov, oldValue, newValue) -> {
if (newValue != null) if (newValue != null)
@ -355,29 +361,29 @@ class CreateOfferPM extends PresentationModel<CreateOfferModel> {
(!newValue)); (!newValue));
// ObservableLists // ObservableLists
model.acceptedCountries.addListener((Observable o) -> acceptedCountries.set(BSFormatter model.acceptedCountries.addListener((Observable o) -> acceptedCountries.set(formatter
.countryLocalesToString(model.acceptedCountries))); .countryLocalesToString(model.acceptedCountries)));
model.acceptedLanguages.addListener((Observable o) -> acceptedLanguages.set(BSFormatter model.acceptedLanguages.addListener((Observable o) -> acceptedLanguages.set(formatter
.languageLocalesToString(model.acceptedLanguages))); .languageLocalesToString(model.acceptedLanguages)));
model.acceptedArbitrators.addListener((Observable o) -> acceptedArbitrators.set(BSFormatter model.acceptedArbitrators.addListener((Observable o) -> acceptedArbitrators.set(formatter
.arbitratorsToString(model.acceptedArbitrators))); .arbitratorsToString(model.acceptedArbitrators)));
} }
private void setupBindings() { private void setupBindings() {
totalToPay.bind(createStringBinding(() -> formatCoinWithCode(model.totalToPayAsCoin.get()), totalToPay.bind(createStringBinding(() -> formatter.formatCoinWithCode(model.totalToPayAsCoin.get()),
model.totalToPayAsCoin)); model.totalToPayAsCoin));
collateral.bind(createStringBinding(() -> formatCoinWithCode(model.collateralAsCoin.get()), collateral.bind(createStringBinding(() -> formatter.formatCoinWithCode(model.collateralAsCoin.get()),
model.collateralAsCoin)); model.collateralAsCoin));
collateralLabel.bind(Bindings.createStringBinding(() -> collateralLabel.bind(Bindings.createStringBinding(() ->
BSResources.get("createOffer.fundsBox.collateral", BSResources.get("createOffer.fundsBox.collateral",
BSFormatter.formatCollateralPercent(model.collateralAsLong.get())), formatter.formatCollateralPercent(model.collateralAsLong.get())),
model.collateralAsLong)); model.collateralAsLong));
totalToPayAsCoin.bind(model.totalToPayAsCoin); totalToPayAsCoin.bind(model.totalToPayAsCoin);
offerFee.bind(createStringBinding(() -> formatCoinWithCode(model.offerFeeAsCoin.get()), offerFee.bind(createStringBinding(() -> formatter.formatCoinWithCode(model.offerFeeAsCoin.get()),
model.offerFeeAsCoin)); model.offerFeeAsCoin));
networkFee.bind(createStringBinding(() -> formatCoinWithCode(model.networkFeeAsCoin.get()), networkFee.bind(createStringBinding(() -> formatter.formatCoinWithCode(model.networkFeeAsCoin.get()),
model.offerFeeAsCoin)); model.offerFeeAsCoin));
bankAccountType.bind(Bindings.createStringBinding(() -> BSResources.get(model.bankAccountType.get()), bankAccountType.bind(Bindings.createStringBinding(() -> BSResources.get(model.bankAccountType.get()),
@ -418,19 +424,19 @@ class CreateOfferPM extends PresentationModel<CreateOfferModel> {
} }
private void setAmountToModel() { private void setAmountToModel() {
model.amountAsCoin.set(parseToCoinWith4Decimals(amount.get())); model.amountAsCoin.set(formatter.parseToCoinWith4Decimals(amount.get()));
} }
private void setMinAmountToModel() { private void setMinAmountToModel() {
model.minAmountAsCoin.set(parseToCoinWith4Decimals(minAmount.get())); model.minAmountAsCoin.set(formatter.parseToCoinWith4Decimals(minAmount.get()));
} }
private void setPriceToModel() { private void setPriceToModel() {
model.priceAsFiat.set(parseToFiatWith2Decimals(price.get())); model.priceAsFiat.set(formatter.parseToFiatWith2Decimals(price.get()));
} }
private void setVolumeToModel() { private void setVolumeToModel() {
model.volumeAsFiat.set(parseToFiatWith2Decimals(volume.get())); model.volumeAsFiat.set(formatter.parseToFiatWith2Decimals(volume.get()));
} }
private void updateButtonDisableState() { private void updateButtonDisableState() {

View file

@ -131,7 +131,8 @@ public class CreateOfferViewCB extends CachedViewCB<CreateOfferPM> {
setupListeners(); setupListeners();
setupBindings(); setupBindings();
balanceTextField.setup(presentationModel.getWalletFacade(), presentationModel.address.get()); balanceTextField.setup(presentationModel.getWalletFacade(), presentationModel.address.get(),
presentationModel.getFormatter());
volumeTextField.setPromptText(BSResources.get("createOffer.volume.prompt", presentationModel.fiatCode.get())); volumeTextField.setPromptText(BSResources.get("createOffer.volume.prompt", presentationModel.fiatCode.get()));
} }

View file

@ -47,7 +47,6 @@ import javafx.collections.transformation.SortedList;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import static io.bitsquare.gui.util.BSFormatter.reduceTo4Decimals;
/** /**
* It holds the scope specific domain data for either a buy or sell UI screen. * It holds the scope specific domain data for either a buy or sell UI screen.
@ -58,6 +57,7 @@ class OrderBookModel extends UIModel {
private final User user; private final User user;
private final OrderBook orderBook; private final OrderBook orderBook;
private final Settings settings; private final Settings settings;
private BSFormatter formatter;
private final TradeManager tradeManager; private final TradeManager tradeManager;
private final FilteredList<OrderBookListItem> filteredItems; private final FilteredList<OrderBookListItem> filteredItems;
@ -85,11 +85,13 @@ class OrderBookModel extends UIModel {
OrderBookModel(User user, OrderBookModel(User user,
TradeManager tradeManager, TradeManager tradeManager,
OrderBook orderBook, OrderBook orderBook,
Settings settings) { Settings settings,
BSFormatter formatter) {
this.tradeManager = tradeManager; this.tradeManager = tradeManager;
this.user = user; this.user = user;
this.orderBook = orderBook; this.orderBook = orderBook;
this.settings = settings; this.settings = settings;
this.formatter = formatter;
filteredItems = new FilteredList<>(orderBook.getOrderBookListItems()); filteredItems = new FilteredList<>(orderBook.getOrderBookListItems());
sortedItems = new SortedList<>(filteredItems); sortedItems = new SortedList<>(filteredItems);
@ -164,7 +166,8 @@ class OrderBookModel extends UIModel {
!volumeAsFiat.get().isZero() && !volumeAsFiat.get().isZero() &&
!priceAsFiat.get().isZero()) { !priceAsFiat.get().isZero()) {
// 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
amountAsCoin.set(reduceTo4Decimals(new ExchangeRate(priceAsFiat.get()).fiatToCoin(volumeAsFiat.get()))); amountAsCoin.set(formatter.reduceTo4Decimals(new ExchangeRate(priceAsFiat.get()).fiatToCoin
(volumeAsFiat.get())));
} }
} catch (Throwable t) { } catch (Throwable t) {
// Should be never reached // Should be never reached
@ -180,7 +183,7 @@ class OrderBookModel extends UIModel {
boolean countryResult = offer.getAcceptedCountries().contains(user.getCurrentBankAccount().getCountry()); boolean countryResult = offer.getAcceptedCountries().contains(user.getCurrentBankAccount().getCountry());
if (!countryResult) if (!countryResult)
restrictionsInfo.set("This offer requires that the payments account resides in one of those countries:\n" + restrictionsInfo.set("This offer requires that the payments account resides in one of those countries:\n" +
BSFormatter.countryLocalesToString(offer.getAcceptedCountries()) + formatter.countryLocalesToString(offer.getAcceptedCountries()) +
"\n\nThe country of your payments account (" + user.getCurrentBankAccount().getCountry().getName() + "\n\nThe country of your payments account (" + user.getCurrentBankAccount().getCountry().getName() +
") is not included in that list."); ") is not included in that list.");

View file

@ -38,12 +38,11 @@ import javafx.collections.transformation.SortedList;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import static io.bitsquare.gui.util.BSFormatter.*;
class OrderBookPM extends PresentationModel<OrderBookModel> { class OrderBookPM extends PresentationModel<OrderBookModel> {
private static final Logger log = LoggerFactory.getLogger(OrderBookPM.class); private static final Logger log = LoggerFactory.getLogger(OrderBookPM.class);
private final OptionalBtcValidator optionalBtcValidator; private final OptionalBtcValidator optionalBtcValidator;
private BSFormatter formatter;
private final OptionalFiatValidator optionalFiatValidator; private final OptionalFiatValidator optionalFiatValidator;
final StringProperty amount = new SimpleStringProperty(); final StringProperty amount = new SimpleStringProperty();
@ -61,11 +60,13 @@ class OrderBookPM extends PresentationModel<OrderBookModel> {
@Inject @Inject
OrderBookPM(OrderBookModel model, OrderBookPM(OrderBookModel model,
OptionalFiatValidator optionalFiatValidator, OptionalFiatValidator optionalFiatValidator,
OptionalBtcValidator optionalBtcValidator) { OptionalBtcValidator optionalBtcValidator,
BSFormatter formatter) {
super(model); super(model);
this.optionalFiatValidator = optionalFiatValidator; this.optionalFiatValidator = optionalFiatValidator;
this.optionalBtcValidator = optionalBtcValidator; this.optionalBtcValidator = optionalBtcValidator;
this.formatter = formatter;
} }
@ -108,9 +109,11 @@ class OrderBookPM extends PresentationModel<OrderBookModel> {
}); });
// Binding with Bindings.createObjectBinding does not work because of bi-directional binding // Binding with Bindings.createObjectBinding does not work because of bi-directional binding
model.amountAsCoinProperty().addListener((ov, oldValue, newValue) -> amount.set(formatCoin(newValue))); model.amountAsCoinProperty().addListener((ov, oldValue, newValue) -> amount.set(formatter.formatCoin
model.priceAsFiatProperty().addListener((ov, oldValue, newValue) -> price.set(formatFiat(newValue))); (newValue)));
model.volumeAsFiatProperty().addListener((ov, oldValue, newValue) -> volume.set(formatFiat(newValue))); model.priceAsFiatProperty().addListener((ov, oldValue, newValue) -> price.set(formatter.formatFiat(newValue)));
model.volumeAsFiatProperty().addListener((ov, oldValue, newValue) -> volume.set(formatter.formatFiat
(newValue)));
} }
@SuppressWarnings("EmptyMethod") @SuppressWarnings("EmptyMethod")
@ -183,17 +186,17 @@ class OrderBookPM extends PresentationModel<OrderBookModel> {
} }
String getAmount(OrderBookListItem item) { String getAmount(OrderBookListItem item) {
return (item != null) ? BSFormatter.formatCoin(item.getOffer().getAmount()) + return (item != null) ? formatter.formatCoin(item.getOffer().getAmount()) +
" (" + BSFormatter.formatCoin(item.getOffer().getMinAmount()) + ")" : ""; " (" + formatter.formatCoin(item.getOffer().getMinAmount()) + ")" : "";
} }
String getPrice(OrderBookListItem item) { String getPrice(OrderBookListItem item) {
return (item != null) ? BSFormatter.formatFiat(item.getOffer().getPrice()) : ""; return (item != null) ? formatter.formatFiat(item.getOffer().getPrice()) : "";
} }
String getVolume(OrderBookListItem item) { String getVolume(OrderBookListItem item) {
return (item != null) ? BSFormatter.formatFiat(item.getOffer().getOfferVolume()) + return (item != null) ? formatter.formatFiat(item.getOffer().getOfferVolume()) +
" (" + BSFormatter.formatFiat(item.getOffer().getMinOfferVolume()) + ")" : ""; " (" + formatter.formatFiat(item.getOffer().getMinOfferVolume()) + ")" : "";
} }
String getBankAccountType(OrderBookListItem item) { String getBankAccountType(OrderBookListItem item) {
@ -201,7 +204,7 @@ class OrderBookPM extends PresentationModel<OrderBookModel> {
} }
String getDirectionLabel(Offer offer) { String getDirectionLabel(Offer offer) {
return BSFormatter.formatDirection(offer.getMirroredDirection()); return formatter.formatDirection(offer.getMirroredDirection());
} }
Direction getDirection() { Direction getDirection() {
@ -229,15 +232,15 @@ class OrderBookPM extends PresentationModel<OrderBookModel> {
} }
private void setAmountToModel() { private void setAmountToModel() {
model.setAmount(parseToCoinWith4Decimals(amount.get())); model.setAmount(formatter.parseToCoinWith4Decimals(amount.get()));
} }
private void setPriceToModel() { private void setPriceToModel() {
model.setPrice(parseToFiatWith2Decimals(price.get())); model.setPrice(formatter.parseToFiatWith2Decimals(price.get()));
} }
private void setVolumeToModel() { private void setVolumeToModel() {
model.setVolume(parseToFiatWith2Decimals(volume.get())); model.setVolume(formatter.parseToFiatWith2Decimals(volume.get()));
} }
} }

View file

@ -41,7 +41,6 @@ import javafx.beans.property.StringProperty;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import static io.bitsquare.gui.util.BSFormatter.*;
import static javafx.beans.binding.Bindings.createStringBinding; import static javafx.beans.binding.Bindings.createStringBinding;
class TakeOfferPM extends PresentationModel<TakeOfferModel> { class TakeOfferPM extends PresentationModel<TakeOfferModel> {
@ -67,6 +66,7 @@ class TakeOfferPM extends PresentationModel<TakeOfferModel> {
final ObjectProperty<Address> address = new SimpleObjectProperty<>(); final ObjectProperty<Address> address = new SimpleObjectProperty<>();
private final BtcValidator btcValidator; private final BtcValidator btcValidator;
private BSFormatter formatter;
final StringProperty amount = new SimpleStringProperty(); final StringProperty amount = new SimpleStringProperty();
final StringProperty volume = new SimpleStringProperty(); final StringProperty volume = new SimpleStringProperty();
@ -94,10 +94,11 @@ class TakeOfferPM extends PresentationModel<TakeOfferModel> {
// non private for testing // non private for testing
@Inject @Inject
TakeOfferPM(TakeOfferModel model, BtcValidator btcValidator) { TakeOfferPM(TakeOfferModel model, BtcValidator btcValidator, BSFormatter formatter) {
super(model); super(model);
this.btcValidator = btcValidator; this.btcValidator = btcValidator;
this.formatter = formatter;
} }
@ -110,8 +111,8 @@ class TakeOfferPM extends PresentationModel<TakeOfferModel> {
super.initialize(); super.initialize();
// static // static
offerFee = formatCoinWithCode(model.offerFeeAsCoin.get()); offerFee = formatter.formatCoinWithCode(model.offerFeeAsCoin.get());
networkFee = formatCoinWithCode(model.networkFeeAsCoin.get()); networkFee = formatter.formatCoinWithCode(model.networkFeeAsCoin.get());
setupBindings(); setupBindings();
setupListeners(); setupListeners();
@ -157,9 +158,9 @@ class TakeOfferPM extends PresentationModel<TakeOfferModel> {
//model.volumeAsFiat.set(offer.getVolumeByAmount(model.amountAsCoin.get())); //model.volumeAsFiat.set(offer.getVolumeByAmount(model.amountAsCoin.get()));
amountRange = BSFormatter.formatCoinWithCode(offer.getMinAmount()) + " - " + amountRange = formatter.formatCoinWithCode(offer.getMinAmount()) + " - " +
BSFormatter.formatCoinWithCode(offer.getAmount()); formatter.formatCoinWithCode(offer.getAmount());
price = BSFormatter.formatFiatWithCode(offer.getPrice()); price = formatter.formatFiatWithCode(offer.getPrice());
paymentLabel = BSResources.get("takeOffer.fundsBox.paymentLabel", offer.getId()); paymentLabel = BSResources.get("takeOffer.fundsBox.paymentLabel", offer.getId());
if (model.getAddressEntry() != null) { if (model.getAddressEntry() != null) {
@ -167,11 +168,11 @@ class TakeOfferPM extends PresentationModel<TakeOfferModel> {
address.set(model.getAddressEntry().getAddress()); address.set(model.getAddressEntry().getAddress());
} }
collateralLabel = BSResources.get("takeOffer.fundsBox.collateral", collateralLabel = BSResources.get("takeOffer.fundsBox.collateral",
BSFormatter.formatCollateralPercent(offer.getCollateral())); formatter.formatCollateralPercent(offer.getCollateral()));
acceptedCountries = BSFormatter.countryLocalesToString(offer.getAcceptedCountries()); acceptedCountries = formatter.countryLocalesToString(offer.getAcceptedCountries());
acceptedLanguages = BSFormatter.languageLocalesToString(offer.getAcceptedLanguageLocales()); acceptedLanguages = formatter.languageLocalesToString(offer.getAcceptedLanguageLocales());
acceptedArbitrators = BSFormatter.arbitratorsToString(offer.getArbitrators()); acceptedArbitrators = formatter.arbitratorsToString(offer.getArbitrators());
bankAccountType = BSResources.get(offer.getBankAccountType().toString()); bankAccountType = BSResources.get(offer.getBankAccountType().toString());
bankAccountCurrency = BSResources.get(offer.getCurrency().getDisplayName()); bankAccountCurrency = BSResources.get(offer.getCurrency().getDisplayName());
bankAccountCounty = BSResources.get(offer.getBankAccountCountry().getName()); bankAccountCounty = BSResources.get(offer.getBankAccountCountry().getName());
@ -206,11 +207,11 @@ class TakeOfferPM extends PresentationModel<TakeOfferModel> {
InputValidator.ValidationResult result = isBtcInputValid(amount.get()); InputValidator.ValidationResult result = isBtcInputValid(amount.get());
amountValidationResult.set(result); amountValidationResult.set(result);
if (result.isValid) { if (result.isValid) {
showWarningInvalidBtcDecimalPlaces.set(!hasBtcValidDecimals(userInput)); showWarningInvalidBtcDecimalPlaces.set(!formatter.hasBtcValidDecimals(userInput));
// only allow max 4 decimal places for btc values // only allow max 4 decimal places for btc values
setAmountToModel(); setAmountToModel();
// reformat input // reformat input
amount.set(formatCoin(model.amountAsCoin.get())); amount.set(formatter.formatCoin(model.amountAsCoin.get()));
calculateVolume(); calculateVolume();
@ -234,6 +235,10 @@ class TakeOfferPM extends PresentationModel<TakeOfferModel> {
return model.getWalletFacade(); return model.getWalletFacade();
} }
BSFormatter getFormatter() {
return formatter;
}
String getOfferFee() { String getOfferFee() {
return offerFee; return offerFee;
} }
@ -318,7 +323,7 @@ class TakeOfferPM extends PresentationModel<TakeOfferModel> {
}); });
// Binding with Bindings.createObjectBinding does not work because of bi-directional binding // Binding with Bindings.createObjectBinding does not work because of bi-directional binding
model.amountAsCoin.addListener((ov, oldValue, newValue) -> amount.set(formatCoin(newValue))); model.amountAsCoin.addListener((ov, oldValue, newValue) -> amount.set(formatter.formatCoin(newValue)));
model.requestTakeOfferErrorMessage.addListener((ov, oldValue, newValue) -> { model.requestTakeOfferErrorMessage.addListener((ov, oldValue, newValue) -> {
if (newValue != null) if (newValue != null)
@ -329,10 +334,11 @@ class TakeOfferPM extends PresentationModel<TakeOfferModel> {
} }
private void setupBindings() { private void setupBindings() {
volume.bind(createStringBinding(() -> formatFiatWithCode(model.volumeAsFiat.get()), model.volumeAsFiat)); volume.bind(createStringBinding(() -> formatter.formatFiatWithCode(model.volumeAsFiat.get()),
totalToPay.bind(createStringBinding(() -> formatCoinWithCode(model.totalToPayAsCoin.get()), model.volumeAsFiat));
totalToPay.bind(createStringBinding(() -> formatter.formatCoinWithCode(model.totalToPayAsCoin.get()),
model.totalToPayAsCoin)); model.totalToPayAsCoin));
collateral.bind(createStringBinding(() -> formatCoinWithCode(model.collateralAsCoin.get()), collateral.bind(createStringBinding(() -> formatter.formatCoinWithCode(model.collateralAsCoin.get()),
model.collateralAsCoin)); model.collateralAsCoin));
totalToPayAsCoin.bind(model.totalToPayAsCoin); totalToPayAsCoin.bind(model.totalToPayAsCoin);
@ -350,7 +356,7 @@ class TakeOfferPM extends PresentationModel<TakeOfferModel> {
} }
private void setAmountToModel() { private void setAmountToModel() {
model.amountAsCoin.set(parseToCoinWith4Decimals(amount.get())); model.amountAsCoin.set(formatter.parseToCoinWith4Decimals(amount.get()));
} }
private void updateButtonDisableState() { private void updateButtonDisableState() {
@ -364,4 +370,5 @@ class TakeOfferPM extends PresentationModel<TakeOfferModel> {
private InputValidator.ValidationResult isBtcInputValid(String input) { private InputValidator.ValidationResult isBtcInputValid(String input) {
return btcValidator.validate(input); return btcValidator.validate(input);
} }
} }

View file

@ -168,7 +168,8 @@ public class TakeOfferViewCB extends CachedViewCB<TakeOfferPM> {
volumeDescriptionLabel.setText(BSResources.get("takeOffer.amountPriceBox.volumeDescription", volumeDescriptionLabel.setText(BSResources.get("takeOffer.amountPriceBox.volumeDescription",
presentationModel.getFiatCode())); presentationModel.getFiatCode()));
balanceTextField.setup(presentationModel.getWalletFacade(), presentationModel.address.get()); balanceTextField.setup(presentationModel.getWalletFacade(), presentationModel.address.get(),
presentationModel.getFormatter());
buyLabel.setText(presentationModel.getDirectionLabel()); buyLabel.setText(presentationModel.getDirectionLabel());
amountRangeTextField.setText(presentationModel.getAmountRange()); amountRangeTextField.setText(presentationModel.getAmountRange());

View file

@ -57,9 +57,9 @@ import static com.google.common.base.Preconditions.*;
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 Locale locale = Locale.getDefault();
private static boolean useMilliBit; private boolean useMilliBit;
private static int scale = 3; private int scale = 3;
// Format use 2 min decimal places and 2 more optional: 1.00 or 1.0010 // Format use 2 min decimal places and 2 more optional: 1.00 or 1.0010
// There are not more then 4 decimals allowed. // There are not more then 4 decimals allowed.
@ -68,12 +68,12 @@ public class BSFormatter {
// Input of a group separator (1,123,45) lead to an validation error. // Input of a group separator (1,123,45) lead to an validation error.
// Note: BtcFormat was intended to be used, but it lead to many problems (automatic format to mBit, // Note: BtcFormat was intended to be used, but it lead to many problems (automatic format to mBit,
// no way to remove grouping separator). It seems to be not optimal for user input formatting. // no way to remove grouping separator). It seems to be not optimal for user input formatting.
private static CoinFormat coinFormat = CoinFormat.BTC.repeatOptionalDecimals(2, 1); private CoinFormat coinFormat = CoinFormat.BTC.repeatOptionalDecimals(2, 1);
private static String currencyCode = Currency.getInstance(Locale.getDefault()).getCurrencyCode(); private String currencyCode = Currency.getInstance(Locale.getDefault()).getCurrencyCode();
// format is like: 1,00 never more then 2 decimals // format is like: 1,00 never more then 2 decimals
private static final CoinFormat fiatFormat = CoinFormat.FIAT.repeatOptionalDecimals(0, 0).code(0, currencyCode); private final CoinFormat fiatFormat = CoinFormat.FIAT.repeatOptionalDecimals(0, 0).code(0, currencyCode);
@Inject @Inject
@ -95,8 +95,8 @@ public class BSFormatter {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
public static void useMilliBitFormat(boolean useMilliBit) { public void useMilliBitFormat(boolean useMilliBit) {
BSFormatter.useMilliBit = useMilliBit; this.useMilliBit = useMilliBit;
coinFormat = getCoinFormat(); coinFormat = getCoinFormat();
scale = useMilliBit ? 0 : 3; scale = useMilliBit ? 0 : 3;
} }
@ -104,19 +104,19 @@ public class BSFormatter {
/** /**
* 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.
*/ */
public static void setLocale(Locale locale) { public void setLocale(Locale locale) {
BSFormatter.locale = locale; this.locale = locale;
} }
private static CoinFormat getCoinFormat() { private CoinFormat getCoinFormat() {
if (useMilliBit) if (useMilliBit)
return CoinFormat.MBTC.repeatOptionalDecimals(2, 1); return CoinFormat.MBTC.repeatOptionalDecimals(2, 1);
else else
return CoinFormat.BTC.repeatOptionalDecimals(2, 1); return CoinFormat.BTC.repeatOptionalDecimals(2, 1);
} }
public static void setFiatCurrencyCode(String currencyCode) { public void setFiatCurrencyCode(String currencyCode) {
BSFormatter.currencyCode = currencyCode; this.currencyCode = currencyCode;
fiatFormat.code(0, currencyCode); fiatFormat.code(0, currencyCode);
} }
@ -125,7 +125,7 @@ public class BSFormatter {
// BTC // BTC
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
public static String formatCoin(Coin coin) { public String formatCoin(Coin coin) {
try { try {
return coinFormat.noCode().format(coin).toString(); return coinFormat.noCode().format(coin).toString();
} catch (Throwable t) { } catch (Throwable t) {
@ -134,7 +134,7 @@ public class BSFormatter {
} }
} }
public static String formatCoinWithCode(Coin coin) { public String formatCoinWithCode(Coin coin) {
try { try {
// we don't use the code feature from coinFormat as it does automatic switching between mBTC and BTC and // we don't use the code feature from coinFormat as it does automatic switching between mBTC and BTC and
// pre and post fixing // pre and post fixing
@ -146,7 +146,7 @@ public class BSFormatter {
} }
public static Coin parseToCoin(String input) { public Coin parseToCoin(String input) {
try { try {
return coinFormat.parse(cleanInput(input)); return coinFormat.parse(cleanInput(input));
} catch (Throwable t) { } catch (Throwable t) {
@ -163,7 +163,7 @@ public class BSFormatter {
* @param input * @param input
* @return * @return
*/ */
public static Coin parseToCoinWith4Decimals(String input) { public Coin parseToCoinWith4Decimals(String input) {
try { try {
return Coin.valueOf(new BigDecimal(parseToCoin(cleanInput(input)).value).setScale(-scale - 1, return Coin.valueOf(new BigDecimal(parseToCoin(cleanInput(input)).value).setScale(-scale - 1,
BigDecimal.ROUND_HALF_UP).setScale(scale + 1).toBigInteger().longValue()); BigDecimal.ROUND_HALF_UP).setScale(scale + 1).toBigInteger().longValue());
@ -173,7 +173,7 @@ public class BSFormatter {
} }
} }
public static boolean hasBtcValidDecimals(String input) { public boolean hasBtcValidDecimals(String input) {
return parseToCoin(input).equals(parseToCoinWith4Decimals(input)); return parseToCoin(input).equals(parseToCoinWith4Decimals(input));
} }
@ -183,7 +183,7 @@ public class BSFormatter {
* @param coin The coin which should be transformed * @param coin The coin which should be transformed
* @return The transformed coin * @return The transformed coin
*/ */
public static Coin reduceTo4Decimals(Coin coin) { public Coin reduceTo4Decimals(Coin coin) {
return parseToCoin(formatCoin(coin)); return parseToCoin(formatCoin(coin));
} }
@ -192,7 +192,7 @@ public class BSFormatter {
// FIAT // FIAT
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
public static String formatFiat(Fiat fiat) { public String formatFiat(Fiat fiat) {
try { try {
return fiatFormat.noCode().format(fiat).toString(); return fiatFormat.noCode().format(fiat).toString();
} catch (Throwable t) { } catch (Throwable t) {
@ -201,7 +201,7 @@ public class BSFormatter {
} }
} }
public static String formatFiatWithCode(Fiat fiat) { public String formatFiatWithCode(Fiat fiat) {
try { try {
return fiatFormat.postfixCode().format(fiat).toString(); return fiatFormat.postfixCode().format(fiat).toString();
} catch (Throwable t) { } catch (Throwable t) {
@ -210,7 +210,7 @@ public class BSFormatter {
} }
} }
public static Fiat parseToFiat(String input) { public Fiat parseToFiat(String input) {
try { try {
return Fiat.parseFiat(currencyCode, cleanInput(input)); return Fiat.parseFiat(currencyCode, cleanInput(input));
} catch (Exception e) { } catch (Exception e) {
@ -226,7 +226,7 @@ public class BSFormatter {
* @param input * @param input
* @return * @return
*/ */
public static Fiat parseToFiatWith2Decimals(String input) { public Fiat parseToFiatWith2Decimals(String input) {
try { try {
return parseToFiat(new BigDecimal(cleanInput(input)).setScale(2, BigDecimal.ROUND_HALF_UP).toString()); return parseToFiat(new BigDecimal(cleanInput(input)).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
} catch (Throwable t) { } catch (Throwable t) {
@ -236,7 +236,7 @@ public class BSFormatter {
} }
public static boolean hasFiatValidDecimals(String input) { public boolean hasFiatValidDecimals(String input) {
return parseToFiat(input).equals(parseToFiatWith2Decimals(input)); return parseToFiat(input).equals(parseToFiatWith2Decimals(input));
} }
@ -251,7 +251,7 @@ public class BSFormatter {
* @return Returns a double value. Any invalid value returns Double.NEGATIVE_INFINITY. * @return Returns a double value. Any invalid value returns Double.NEGATIVE_INFINITY.
*/ */
@Deprecated //TODO use Fiat or Btc if possible @Deprecated //TODO use Fiat or Btc if possible
public static double parseToDouble(String input) { public double parseToDouble(String input) {
try { try {
checkNotNull(input); checkNotNull(input);
checkArgument(input.length() > 0); checkArgument(input.length() > 0);
@ -262,11 +262,11 @@ public class BSFormatter {
} }
} }
public static String formatDirection(Direction direction) { public String formatDirection(Direction direction) {
return formatDirection(direction, true); return formatDirection(direction, true);
} }
public static String formatDirection(Direction direction, boolean allUpperCase) { public String formatDirection(Direction direction, boolean allUpperCase) {
String result = (direction == Direction.BUY) ? "Buy" : "Sell"; String result = (direction == Direction.BUY) ? "Buy" : "Sell";
if (allUpperCase) { if (allUpperCase) {
result = result.toUpperCase(); result = result.toUpperCase();
@ -274,47 +274,47 @@ public class BSFormatter {
return result; return result;
} }
public static String formatAmountWithMinAmount(Offer offer) { public String formatAmountWithMinAmount(Offer offer) {
return formatCoin(offer.getAmount()) + " (" + BSFormatter.formatCoin(offer.getMinAmount()) + ")"; return formatCoin(offer.getAmount()) + " (" + formatCoin(offer.getMinAmount()) + ")";
} }
public static String formatVolumeWithMinVolume(Offer offer) { public String formatVolumeWithMinVolume(Offer offer) {
return BSFormatter.formatFiat(offer.getOfferVolume()) + return formatFiat(offer.getOfferVolume()) +
" (" + BSFormatter.formatFiat(offer.getMinOfferVolume()) + ")"; " (" + formatFiat(offer.getMinOfferVolume()) + ")";
} }
public static String countryLocalesToString(List<Country> countries) { public String countryLocalesToString(List<Country> countries) {
return countries.stream().map(Country::getName).collect(Collectors.joining(", ")); return countries.stream().map(Country::getName).collect(Collectors.joining(", "));
} }
public static String arbitratorsToString(List<Arbitrator> arbitrators) { public String arbitratorsToString(List<Arbitrator> arbitrators) {
return arbitrators.stream().map(Arbitrator::getName).collect(Collectors.joining(", ")); return arbitrators.stream().map(Arbitrator::getName).collect(Collectors.joining(", "));
} }
public static String languageLocalesToString(List<Locale> languageLocales) { public String languageLocalesToString(List<Locale> languageLocales) {
return languageLocales.stream().map(e -> e.getDisplayLanguage()).collect(Collectors.joining(", ")); return languageLocales.stream().map(e -> e.getDisplayLanguage()).collect(Collectors.joining(", "));
} }
public static String arbitrationMethodsToString(List<Arbitrator.METHOD> methods) { public String arbitrationMethodsToString(List<Arbitrator.METHOD> methods) {
return methods.stream().map(e -> BSResources.get(e.toString())).collect(Collectors.joining(", ")); return methods.stream().map(e -> BSResources.get(e.toString())).collect(Collectors.joining(", "));
} }
public static String arbitrationIDVerificationsToString(List<Arbitrator.ID_VERIFICATION> items) { public String arbitrationIDVerificationsToString(List<Arbitrator.ID_VERIFICATION> items) {
return items.stream().map(e -> BSResources.get(e.toString())).collect(Collectors.joining(", ")); return items.stream().map(e -> BSResources.get(e.toString())).collect(Collectors.joining(", "));
} }
public static String mnemonicCodeToString(List<String> mnemonicCode) { public String mnemonicCodeToString(List<String> mnemonicCode) {
return mnemonicCode.stream().collect(Collectors.joining(" ")); return mnemonicCode.stream().collect(Collectors.joining(" "));
} }
public static String formatDateTime(Date date) { public String formatDateTime(Date date) {
DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, locale); DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
DateFormat timeFormatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale); DateFormat timeFormatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
return dateFormatter.format(date) + " " + timeFormatter.format(date); return dateFormatter.format(date) + " " + timeFormatter.format(date);
} }
public static String formatCollateralPercent(long collateral) { public String formatCollateralPercent(long collateral) {
DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(locale); DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(locale);
decimalFormat.setMinimumFractionDigits(1); decimalFormat.setMinimumFractionDigits(1);
decimalFormat.setMaximumFractionDigits(1); decimalFormat.setMaximumFractionDigits(1);
@ -322,7 +322,7 @@ public class BSFormatter {
return decimalFormat.format(collateral / 10) + " %"; return decimalFormat.format(collateral / 10) + " %";
} }
public static String formatToPercent(double value) { public String formatToPercent(double value) {
DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(locale); DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(locale);
decimalFormat.setMinimumFractionDigits(1); decimalFormat.setMinimumFractionDigits(1);
decimalFormat.setMaximumFractionDigits(1); decimalFormat.setMaximumFractionDigits(1);
@ -330,7 +330,7 @@ public class BSFormatter {
return decimalFormat.format(value / 100) + " %"; return decimalFormat.format(value / 100) + " %";
} }
private static String cleanInput(String input) { private String cleanInput(String input) {
input = input.replace(",", "."); input = input.replace(",", ".");
// don't use String.valueOf(Double.parseDouble(input)) as return value as it gives scientific // don't use String.valueOf(Double.parseDouble(input)) as return value as it gives scientific
// notation (1.0E-6) which screw up coinFormat.parse // notation (1.0E-6) which screw up coinFormat.parse

View file

@ -20,7 +20,6 @@ package io.bitsquare;
import io.bitsquare.btc.RestrictionsTest; import io.bitsquare.btc.RestrictionsTest;
import io.bitsquare.gui.main.trade.createoffer.CreateOfferPMTest; import io.bitsquare.gui.main.trade.createoffer.CreateOfferPMTest;
import io.bitsquare.gui.util.BSFormatterTest; import io.bitsquare.gui.util.BSFormatterTest;
import io.bitsquare.gui.util.BitSquareConverterTest;
import io.bitsquare.gui.util.validation.BtcValidatorTest; import io.bitsquare.gui.util.validation.BtcValidatorTest;
import io.bitsquare.gui.util.validation.FiatValidatorTest; import io.bitsquare.gui.util.validation.FiatValidatorTest;
import io.bitsquare.msg.P2PNodeTest; import io.bitsquare.msg.P2PNodeTest;
@ -31,7 +30,6 @@ import org.junit.runners.Suite;
@RunWith(Suite.class) @RunWith(Suite.class)
@Suite.SuiteClasses({ @Suite.SuiteClasses({
RestrictionsTest.class, RestrictionsTest.class,
BitSquareConverterTest.class,
P2PNodeTest.class, P2PNodeTest.class,
FiatValidatorTest.class, FiatValidatorTest.class,
RestrictionsTest.class, RestrictionsTest.class,

View file

@ -22,6 +22,7 @@ import io.bitsquare.gui.util.BSFormatter;
import io.bitsquare.gui.util.validation.BtcValidator; import io.bitsquare.gui.util.validation.BtcValidator;
import io.bitsquare.gui.util.validation.FiatValidator; import io.bitsquare.gui.util.validation.FiatValidator;
import io.bitsquare.locale.Country; import io.bitsquare.locale.Country;
import io.bitsquare.user.User;
import com.google.bitcoin.core.Coin; import com.google.bitcoin.core.Coin;
import com.google.bitcoin.utils.Fiat; import com.google.bitcoin.utils.Fiat;
@ -44,12 +45,12 @@ public class CreateOfferPMTest {
@Before @Before
public void setup() { public void setup() {
model = new CreateOfferModel(null, null, null, null); BSFormatter formatter = new BSFormatter(new User());
formatter.setLocale(Locale.US);
formatter.setFiatCurrencyCode("USD");
model = new CreateOfferModel(null, null, null, null, formatter);
BSFormatter.setLocale(Locale.US); presenter = new CreateOfferPM(model, new FiatValidator(null), new BtcValidator(), formatter);
BSFormatter.setFiatCurrencyCode("USD");
presenter = new CreateOfferPM(model, new FiatValidator(null), new BtcValidator());
presenter.initialize(); presenter.initialize();
} }

View file

@ -17,6 +17,8 @@
package io.bitsquare.gui.util; package io.bitsquare.gui.util;
import io.bitsquare.user.User;
import com.google.bitcoin.core.Coin; import com.google.bitcoin.core.Coin;
import java.util.Locale; import java.util.Locale;
@ -26,7 +28,6 @@ import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import static io.bitsquare.gui.util.BSFormatter.*;
import static org.junit.Assert.*; import static org.junit.Assert.*;
public class BSFormatterTest { public class BSFormatterTest {
@ -34,136 +35,143 @@ public class BSFormatterTest {
@Test @Test
public void testParseToBtc() { public void testParseToBtc() {
useMilliBitFormat(false); BSFormatter formatter = new BSFormatter(new User());
assertEquals(Coin.ZERO, parseToCoin("0")); formatter.useMilliBitFormat(false);
assertEquals(Coin.COIN, parseToCoin("1")); assertEquals(Coin.ZERO, formatter.parseToCoin("0"));
assertEquals(Coin.SATOSHI, parseToCoin("0,00000001")); assertEquals(Coin.COIN, formatter.parseToCoin("1"));
assertEquals(Coin.SATOSHI, formatter.parseToCoin("0,00000001"));
assertEquals(Coin.parseCoin("-1"), parseToCoin("-1")); assertEquals(Coin.parseCoin("-1"), formatter.parseToCoin("-1"));
assertEquals(Coin.parseCoin("1.1"), parseToCoin("1,1")); assertEquals(Coin.parseCoin("1.1"), formatter.parseToCoin("1,1"));
assertEquals(Coin.parseCoin("1.1"), parseToCoin("1.1")); assertEquals(Coin.parseCoin("1.1"), formatter.parseToCoin("1.1"));
assertEquals(Coin.parseCoin("0"), parseToCoin("1.123,45")); assertEquals(Coin.parseCoin("0"), formatter.parseToCoin("1.123,45"));
assertEquals(Coin.parseCoin("0"), parseToCoin("1,123.45")); assertEquals(Coin.parseCoin("0"), formatter.parseToCoin("1,123.45"));
assertEquals(Coin.parseCoin("1.1234"), parseToCoinWith4Decimals("1,12342")); assertEquals(Coin.parseCoin("1.1234"), formatter.parseToCoinWith4Decimals("1,12342"));
assertEquals(Coin.parseCoin("1.1235"), parseToCoinWith4Decimals("1,12345")); assertEquals(Coin.parseCoin("1.1235"), formatter.parseToCoinWith4Decimals("1,12345"));
assertEquals(Coin.parseCoin("1.1230"), parseToCoinWith4Decimals("1,123")); assertEquals(Coin.parseCoin("1.1230"), formatter.parseToCoinWith4Decimals("1,123"));
// change to mBTC // change to mBTC
useMilliBitFormat(true); formatter.useMilliBitFormat(true);
assertEquals(Coin.parseCoin("1"), parseToCoin("1000")); assertEquals(Coin.parseCoin("1"), formatter.parseToCoin("1000"));
assertEquals(Coin.parseCoin("0.123"), parseToCoin("123")); assertEquals(Coin.parseCoin("0.123"), formatter.parseToCoin("123"));
assertEquals(Coin.parseCoin("0.1234"), parseToCoin("123.4")); assertEquals(Coin.parseCoin("0.1234"), formatter.parseToCoin("123.4"));
assertEquals(Coin.parseCoin("0.12345"), parseToCoin("123.45")); assertEquals(Coin.parseCoin("0.12345"), formatter.parseToCoin("123.45"));
assertEquals(Coin.parseCoin("0.123456"), parseToCoin("123.456")); assertEquals(Coin.parseCoin("0.123456"), formatter.parseToCoin("123.456"));
assertEquals(Coin.parseCoin("0"), parseToCoin("123,456.7")); assertEquals(Coin.parseCoin("0"), formatter.parseToCoin("123,456.7"));
assertEquals(Coin.parseCoin("0.001123"), parseToCoinWith4Decimals("1.123")); assertEquals(Coin.parseCoin("0.001123"), formatter.parseToCoinWith4Decimals("1.123"));
assertEquals(Coin.parseCoin("0.0011234"), parseToCoinWith4Decimals("1.1234")); assertEquals(Coin.parseCoin("0.0011234"), formatter.parseToCoinWith4Decimals("1.1234"));
assertEquals(Coin.parseCoin("0.0011234"), parseToCoinWith4Decimals("1.12342")); assertEquals(Coin.parseCoin("0.0011234"), formatter.parseToCoinWith4Decimals("1.12342"));
assertEquals(Coin.parseCoin("0.0011235"), parseToCoinWith4Decimals("1.12345")); assertEquals(Coin.parseCoin("0.0011235"), formatter.parseToCoinWith4Decimals("1.12345"));
} }
@Test @Test
public void testFormatCoin() { public void testFormatCoin() {
useMilliBitFormat(false); BSFormatter formatter = new BSFormatter(new User());
assertEquals("1.00", formatCoin(Coin.COIN)); formatter.useMilliBitFormat(false);
assertEquals("1.0120", formatCoin(Coin.parseCoin("1.012"))); assertEquals("1.00", formatter.formatCoin(Coin.COIN));
assertEquals("1012.30", formatCoin(Coin.parseCoin("1012.3"))); assertEquals("1.0120", formatter.formatCoin(Coin.parseCoin("1.012")));
assertEquals("1.0120", formatCoin(Coin.parseCoin("1.01200"))); assertEquals("1012.30", formatter.formatCoin(Coin.parseCoin("1012.3")));
assertEquals("1.0123", formatCoin(Coin.parseCoin("1.01234"))); assertEquals("1.0120", formatter.formatCoin(Coin.parseCoin("1.01200")));
assertEquals("1.0123", formatter.formatCoin(Coin.parseCoin("1.01234")));
assertEquals("1.2345", formatCoin(Coin.parseCoin("1.2345"))); assertEquals("1.2345", formatter.formatCoin(Coin.parseCoin("1.2345")));
assertEquals("1.2346", formatCoin(Coin.parseCoin("1.23456"))); assertEquals("1.2346", formatter.formatCoin(Coin.parseCoin("1.23456")));
assertEquals("1.2346", formatCoin(Coin.parseCoin("1.234567"))); assertEquals("1.2346", formatter.formatCoin(Coin.parseCoin("1.234567")));
assertEquals("1.2345", formatCoin(Coin.parseCoin("1.23448"))); assertEquals("1.2345", formatter.formatCoin(Coin.parseCoin("1.23448")));
assertEquals("1.00", formatCoin(Coin.COIN)); assertEquals("1.00", formatter.formatCoin(Coin.COIN));
assertEquals("1012.30", formatCoin(Coin.parseCoin("1012.3"))); assertEquals("1012.30", formatter.formatCoin(Coin.parseCoin("1012.3")));
// change to mBTC // change to mBTC
useMilliBitFormat(true); formatter.useMilliBitFormat(true);
assertEquals("1000.00", formatCoin(Coin.COIN)); assertEquals("1000.00", formatter.formatCoin(Coin.COIN));
assertEquals("1.00", formatCoin(Coin.MILLICOIN)); assertEquals("1.00", formatter.formatCoin(Coin.MILLICOIN));
assertEquals("0.0010", formatCoin(Coin.MICROCOIN)); assertEquals("0.0010", formatter.formatCoin(Coin.MICROCOIN));
} }
@Test @Test
public void testFormatCoinWithCode() { public void testFormatCoinWithCode() {
useMilliBitFormat(false); BSFormatter formatter = new BSFormatter(new User());
assertEquals("1.00 BTC", formatCoinWithCode(Coin.COIN)); formatter.useMilliBitFormat(false);
assertEquals("1.01 BTC", formatCoinWithCode(Coin.parseCoin("1.01"))); assertEquals("1.00 BTC", formatter.formatCoinWithCode(Coin.COIN));
assertEquals("1.0120 BTC", formatCoinWithCode(Coin.parseCoin("1.012"))); assertEquals("1.01 BTC", formatter.formatCoinWithCode(Coin.parseCoin("1.01")));
assertEquals("1012.30 BTC", formatCoinWithCode(Coin.parseCoin("1012.3"))); assertEquals("1.0120 BTC", formatter.formatCoinWithCode(Coin.parseCoin("1.012")));
assertEquals("1.0120 BTC", formatCoinWithCode(Coin.parseCoin("1.01200"))); assertEquals("1012.30 BTC", formatter.formatCoinWithCode(Coin.parseCoin("1012.3")));
assertEquals("1.0123 BTC", formatCoinWithCode(Coin.parseCoin("1.01234"))); assertEquals("1.0120 BTC", formatter.formatCoinWithCode(Coin.parseCoin("1.01200")));
assertEquals("1.0123 BTC", formatter.formatCoinWithCode(Coin.parseCoin("1.01234")));
assertEquals("1.2345 BTC", formatCoinWithCode(Coin.parseCoin("1.2345"))); assertEquals("1.2345 BTC", formatter.formatCoinWithCode(Coin.parseCoin("1.2345")));
assertEquals("1.2346 BTC", formatCoinWithCode(Coin.parseCoin("1.23456"))); assertEquals("1.2346 BTC", formatter.formatCoinWithCode(Coin.parseCoin("1.23456")));
assertEquals("1.2346 BTC", formatCoinWithCode(Coin.parseCoin("1.234567"))); assertEquals("1.2346 BTC", formatter.formatCoinWithCode(Coin.parseCoin("1.234567")));
assertEquals("1.2345 BTC", formatCoinWithCode(Coin.parseCoin("1.23448"))); assertEquals("1.2345 BTC", formatter.formatCoinWithCode(Coin.parseCoin("1.23448")));
assertEquals("1.00 BTC", formatCoinWithCode(Coin.COIN)); assertEquals("1.00 BTC", formatter.formatCoinWithCode(Coin.COIN));
assertEquals("1012.30 BTC", formatCoinWithCode(Coin.parseCoin("1012.3"))); assertEquals("1012.30 BTC", formatter.formatCoinWithCode(Coin.parseCoin("1012.3")));
// change to mBTC // change to mBTC
useMilliBitFormat(true); formatter.useMilliBitFormat(true);
assertEquals("1000.00 mBTC", formatCoinWithCode(Coin.COIN)); assertEquals("1000.00 mBTC", formatter.formatCoinWithCode(Coin.COIN));
assertEquals("1.00 mBTC", formatCoinWithCode(Coin.MILLICOIN)); assertEquals("1.00 mBTC", formatter.formatCoinWithCode(Coin.MILLICOIN));
assertEquals("0.0010 mBTC", formatCoinWithCode(Coin.MICROCOIN)); assertEquals("0.0010 mBTC", formatter.formatCoinWithCode(Coin.MICROCOIN));
} }
@Test @Test
public void testParseToBtcWith4Decimals() { public void testParseToBtcWith4Decimals() {
useMilliBitFormat(false); BSFormatter formatter = new BSFormatter(new User());
assertEquals(Coin.parseCoin("0"), parseToCoinWith4Decimals("0")); formatter.useMilliBitFormat(false);
assertEquals(Coin.parseCoin("0"), parseToCoinWith4Decimals(null)); assertEquals(Coin.parseCoin("0"), formatter.parseToCoinWith4Decimals("0"));
assertEquals(Coin.parseCoin("0"), parseToCoinWith4Decimals("s")); assertEquals(Coin.parseCoin("0"), formatter.parseToCoinWith4Decimals(null));
assertEquals(Coin.parseCoin("0.0012"), parseToCoinWith4Decimals("0,00123")); assertEquals(Coin.parseCoin("0"), formatter.parseToCoinWith4Decimals("s"));
assertEquals(Coin.parseCoin("0.0013"), parseToCoinWith4Decimals("0,00125")); assertEquals(Coin.parseCoin("0.0012"), formatter.parseToCoinWith4Decimals("0,00123"));
assertEquals(Coin.parseCoin("0.0013"), formatter.parseToCoinWith4Decimals("0,00125"));
} }
@Test @Test
public void testHasBtcValidDecimals() { public void testHasBtcValidDecimals() {
useMilliBitFormat(false); BSFormatter formatter = new BSFormatter(new User());
setLocale(Locale.GERMAN); formatter.useMilliBitFormat(false);
assertTrue(hasBtcValidDecimals(null)); formatter.setLocale(Locale.GERMAN);
assertTrue(hasBtcValidDecimals("0")); assertTrue(formatter.hasBtcValidDecimals(null));
assertTrue(hasBtcValidDecimals("0,0001")); assertTrue(formatter.hasBtcValidDecimals("0"));
assertTrue(hasBtcValidDecimals("0.0001")); assertTrue(formatter.hasBtcValidDecimals("0,0001"));
assertTrue(hasBtcValidDecimals("0.0009")); assertTrue(formatter.hasBtcValidDecimals("0.0001"));
assertTrue(hasBtcValidDecimals("20000000.0001")); assertTrue(formatter.hasBtcValidDecimals("0.0009"));
assertFalse(hasBtcValidDecimals("20000000.000123")); assertTrue(formatter.hasBtcValidDecimals("20000000.0001"));
assertFalse(hasBtcValidDecimals("0.00012")); assertFalse(formatter.hasBtcValidDecimals("20000000.000123"));
assertFalse(hasBtcValidDecimals("0.0001222312312312313")); assertFalse(formatter.hasBtcValidDecimals("0.00012"));
assertFalse(formatter.hasBtcValidDecimals("0.0001222312312312313"));
} }
@Test @Test
public void testParseToFiatWith2Decimals() { public void testParseToFiatWith2Decimals() {
useMilliBitFormat(false); BSFormatter formatter = new BSFormatter(new User());
setLocale(Locale.GERMAN); formatter.useMilliBitFormat(false);
assertEquals("0", parseToFiatWith2Decimals("0").toPlainString()); formatter.setLocale(Locale.GERMAN);
assertEquals("0", parseToFiatWith2Decimals(null).toPlainString()); assertEquals("0", formatter.parseToFiatWith2Decimals("0").toPlainString());
assertEquals("0", parseToFiatWith2Decimals("s").toPlainString()); assertEquals("0", formatter.parseToFiatWith2Decimals(null).toPlainString());
assertEquals("0.12", parseToFiatWith2Decimals("0.123").toPlainString()); assertEquals("0", formatter.parseToFiatWith2Decimals("s").toPlainString());
assertEquals("0.13", parseToFiatWith2Decimals("0.125").toPlainString()); assertEquals("0.12", formatter.parseToFiatWith2Decimals("0.123").toPlainString());
assertEquals("0.13", parseToFiatWith2Decimals("0,125").toPlainString()); assertEquals("0.13", formatter.parseToFiatWith2Decimals("0.125").toPlainString());
assertEquals("0.13", formatter.parseToFiatWith2Decimals("0,125").toPlainString());
} }
@Test @Test
public void testHasFiatValidDecimals() { public void testHasFiatValidDecimals() {
useMilliBitFormat(false); BSFormatter formatter = new BSFormatter(new User());
setLocale(Locale.GERMAN); formatter.useMilliBitFormat(false);
assertTrue(hasFiatValidDecimals(null)); formatter.setLocale(Locale.GERMAN);
assertTrue(hasFiatValidDecimals("0")); assertTrue(formatter.hasFiatValidDecimals(null));
assertTrue(hasFiatValidDecimals("0,01")); assertTrue(formatter.hasFiatValidDecimals("0"));
assertTrue(hasFiatValidDecimals("0.01")); assertTrue(formatter.hasFiatValidDecimals("0,01"));
assertTrue(hasFiatValidDecimals("0.09")); assertTrue(formatter.hasFiatValidDecimals("0.01"));
assertTrue(hasFiatValidDecimals("20000000.01")); assertTrue(formatter.hasFiatValidDecimals("0.09"));
assertFalse(hasFiatValidDecimals("20000000.0123")); assertTrue(formatter.hasFiatValidDecimals("20000000.01"));
assertFalse(hasFiatValidDecimals("0.012")); assertFalse(formatter.hasFiatValidDecimals("20000000.0123"));
assertFalse(hasFiatValidDecimals("0.01222312312312313")); assertFalse(formatter.hasFiatValidDecimals("0.012"));
assertFalse(formatter.hasFiatValidDecimals("0.01222312312312313"));
} }
} }

View file

@ -1,44 +0,0 @@
/*
* This file is part of Bitsquare.
*
* Bitsquare is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* Bitsquare is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Bitsquare. If not, see <http://www.gnu.org/licenses/>.
*/
package io.bitsquare.gui.util;
import org.junit.Test;
import static org.junit.Assert.*;
public class BitSquareConverterTest {
@Test
public void testStringToDouble() {
assertEquals(1, BSFormatter.parseToDouble("1"), 0);
assertEquals(0.1, BSFormatter.parseToDouble("0.1"), 0);
assertEquals(0.1, BSFormatter.parseToDouble("0,1"), 0);
assertEquals(1, BSFormatter.parseToDouble("1.0"), 0);
assertEquals(1, BSFormatter.parseToDouble("1,0"), 0);
assertEquals(0, BSFormatter.parseToDouble("1,000.2"), 0);
assertEquals(0, BSFormatter.parseToDouble("1,000.2"), 0);
assertEquals(0, BSFormatter.parseToDouble(null), 0);
assertEquals(0, BSFormatter.parseToDouble(""), 0);
assertEquals(0, BSFormatter.parseToDouble(""), 0);
assertEquals(0, BSFormatter.parseToDouble("."), 0);
assertEquals(0, BSFormatter.parseToDouble(","), 0);
assertEquals(0, BSFormatter.parseToDouble("a"), 0);
}
}