Simplify balance parsing logic

This commit is contained in:
Sylvia van Os
2021-02-22 20:21:24 +01:00
parent 9f914d4943
commit 45c71f01c2
3 changed files with 53 additions and 22 deletions

View File

@@ -214,11 +214,11 @@ public class LoyaltyCardEditActivity extends AppCompatActivity
hasChanged = true;
try {
BigDecimal balance = Utils.parseCurrencyInUserLocale(s.toString());
BigDecimal balance = Utils.parseCurrency(s.toString());
validBalance = true;
balanceField.setTag(balance);
} catch (ParseException | NumberFormatException e) {
} catch (NumberFormatException e) {
validBalance = false;
e.printStackTrace();
}
@@ -500,13 +500,10 @@ public class LoyaltyCardEditActivity extends AppCompatActivity
break;
}
}
chip.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
hasChanged = true;
chip.setOnTouchListener((v, event) -> {
hasChanged = true;
return false;
}
return false;
});
groupsChips.addView(chip);
@@ -565,12 +562,7 @@ public class LoyaltyCardEditActivity extends AppCompatActivity
barcodeTypeField.setAdapter(barcodeAdapter);
FloatingActionButton saveButton = findViewById(R.id.fabSave);
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
doSave();
}
});
saveButton.setOnClickListener(v -> doSave());
generateIcon(storeFieldEdit.getText().toString());
}

View File

@@ -13,6 +13,7 @@ import java.util.Calendar;
import java.util.Currency;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import androidx.core.graphics.ColorUtils;
@@ -111,15 +112,17 @@ public class Utils {
return numberFormat.format(value);
}
static public BigDecimal parseCurrencyInUserLocale(String value) throws ParseException, NumberFormatException {
// BigDecimal only likes to parse in US locale
// So we have to translate whatever the input was to US locale
NumberFormat numberInputFormat = NumberFormat.getNumberInstance();
NumberFormat numberToBigDecimalFormat = NumberFormat.getNumberInstance(Locale.US);
static public BigDecimal parseCurrency(String value) throws NumberFormatException {
// There are many ways users can write a currency, so we fix it up a bit
// 1. Replace all commas with dots
value = value.replace(',', '.');
// BigDecimal won't understand values like 1,000 instead of 1000
numberToBigDecimalFormat.setGroupingUsed(false);
// 2. Remove all but the last dot
while (value.split("\\.").length > 2) {
value = value.replaceFirst("\\.", "");
}
return new BigDecimal(numberToBigDecimalFormat.format(numberInputFormat.parse(value)));
// Parse as BigDecimal
return new BigDecimal(value);
}
}