changed handling of percentage parsing

This commit is contained in:
Sven Vogel 2023-07-12 21:48:19 +02:00
parent 8bf68f5d66
commit 22a15c3bb9
2 changed files with 22 additions and 8 deletions

View File

@ -2,6 +2,7 @@ package me.teridax.jcash.banking.management;
import me.teridax.jcash.banking.Bank;
import me.teridax.jcash.banking.accounts.Account;
import me.teridax.jcash.banking.accounts.CurrentAccount;
import me.teridax.jcash.banking.accounts.Owner;
import me.teridax.jcash.decode.StringDecoder;

View File

@ -37,13 +37,24 @@ public class StringDecoder {
Objects.requireNonNull(number);
// trim the number and cut out optional percent symbols
var trimmed = number.trim().replace("%", "");
var trimmed = number.trim();
var pattern = Pattern.compile("^([^%]+)?(%)?$", Pattern.CASE_INSENSITIVE);
var matcher = pattern.matcher(trimmed);
if (matcher.find()) {
var scale = 1e2;
if (null != matcher.group(2))
scale = 1;
try {
return LOCAL_NUMBER_FORMAT.parse(trimmed).doubleValue();
return LOCAL_NUMBER_FORMAT.parse(matcher.group(1)).doubleValue() * scale;
} catch (ParseException ex) {
throw new IllegalArgumentException("Not a valid number: " + number, ex);
}
} else {
throw new IllegalArgumentException("not a valid percentage");
}
}
/**
@ -138,6 +149,8 @@ public class StringDecoder {
@Test
public void testDecodeSuccessfulFunctions() {
assertEquals(decodePercent("1,003"), 100.3d, 1e-3d);
decodeUniqueIdentificationNumber("9578647895");
decodeUniqueIdentificationNumber(" 927856347 ");
decodeUniqueIdentificationNumber("0");
@ -150,9 +163,9 @@ public class StringDecoder {
decodeStreet("Gülleweg 9");
decodeStreet("Echsengaße 67 / 4");
assertEquals(decodePercent("1,4%"), 1.4d);
assertEquals(decodePercent("99"), 99.0d);
assertEquals(decodePercent("1,003 %"), 1.003d);
assertEquals(decodePercent("1,4%"), 1.4, 1e-3d);
assertEquals(decodePercent("99"), 9900.0d);
assertEquals(decodePercent("1,003%"), 1.003, 1e-5d);
assertEquals(decodeCurrency("1,3€"), 1.3d);
assertEquals(decodeCurrency("145,34"), 145,34d);