From 22a15c3bb9607c866356eec79d824be5395cdbf5 Mon Sep 17 00:00:00 2001 From: teridax Date: Wed, 12 Jul 2023 21:48:19 +0200 Subject: [PATCH] changed handling of percentage parsing --- .../management/BankingManagementSystem.java | 1 + .../teridax/jcash/decode/StringDecoder.java | 29 ++++++++++++++----- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/src/me/teridax/jcash/banking/management/BankingManagementSystem.java b/src/me/teridax/jcash/banking/management/BankingManagementSystem.java index 2fc6536..ba7c0fc 100644 --- a/src/me/teridax/jcash/banking/management/BankingManagementSystem.java +++ b/src/me/teridax/jcash/banking/management/BankingManagementSystem.java @@ -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; diff --git a/src/me/teridax/jcash/decode/StringDecoder.java b/src/me/teridax/jcash/decode/StringDecoder.java index 86b7cd3..86751b6 100644 --- a/src/me/teridax/jcash/decode/StringDecoder.java +++ b/src/me/teridax/jcash/decode/StringDecoder.java @@ -37,12 +37,23 @@ public class StringDecoder { Objects.requireNonNull(number); // trim the number and cut out optional percent symbols - var trimmed = number.trim().replace("%", ""); + var trimmed = number.trim(); - try { - return LOCAL_NUMBER_FORMAT.parse(trimmed).doubleValue(); - } catch (ParseException ex) { - throw new IllegalArgumentException("Not a valid number: " + number, ex); + 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(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);