From d950ff439017c6f22b1efabf08df1fe0f4a5674a Mon Sep 17 00:00:00 2001 From: Damyan Ivanov Date: Sat, 30 Jan 2021 16:35:46 +0200 Subject: [PATCH] rename formatNumber to formatCurrency and provide formatNumber w/o curr. also provide number parsing, using the same NumberFormat object --- .../net/ktnx/mobileledger/model/Data.java | 27 +++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/net/ktnx/mobileledger/model/Data.java b/app/src/main/java/net/ktnx/mobileledger/model/Data.java index 4d0e52a5..dfd1cd67 100644 --- a/app/src/main/java/net/ktnx/mobileledger/model/Data.java +++ b/app/src/main/java/net/ktnx/mobileledger/model/Data.java @@ -1,5 +1,5 @@ /* - * Copyright © 2020 Damyan Ivanov. + * Copyright © 2021 Damyan Ivanov. * This file is part of MoLe. * MoLe is free software: you can distribute it and/or modify it * under the term of the GNU General Public License as published by @@ -35,6 +35,8 @@ import net.ktnx.mobileledger.utils.MLDB; import net.ktnx.mobileledger.utils.ObservableValue; import java.text.NumberFormat; +import java.text.ParseException; +import java.text.ParsePosition; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -67,6 +69,7 @@ public final class Data { new InertMutableLiveData<>(); private static final AtomicInteger backgroundTaskCount = new AtomicInteger(0); private static final Locker profilesLocker = new Locker(); + private static NumberFormat numberFormatter; static { locale.setValue(Locale.getDefault()); @@ -189,11 +192,23 @@ public final class Data { } else currencySymbolPosition.setValue(Currency.Position.none); + + NumberFormat newNumberFormatter = NumberFormat.getNumberInstance(); + newNumberFormatter.setParseIntegerOnly(false); + newNumberFormatter.setGroupingUsed(true); + newNumberFormatter.setGroupingUsed(true); + newNumberFormatter.setMinimumIntegerDigits(1); + newNumberFormatter.setMinimumFractionDigits(2); + + numberFormatter = newNumberFormatter; } - public static String formatNumber(float number) { + public static String formatCurrency(float number) { NumberFormat formatter = NumberFormat.getCurrencyInstance(locale.getValue()); return formatter.format(number); } + public static String formatNumber(float number) { + return numberFormatter.format(number); + } public static void observeProfile(LifecycleOwner lifecycleOwner, Observer observer) { profile.observe(lifecycleOwner, observer); @@ -214,4 +229,12 @@ public final class Data { public static void removeProfileObservers(LifecycleOwner owner) { profile.removeObservers(owner); } + public static float parseNumber(String str) throws ParseException { + ParsePosition pos = new ParsePosition(0); + Number parsed = numberFormatter.parse(str); + if (parsed == null) + throw new ParseException("Error parsing '" + str + "'", pos.getErrorIndex()); + + return (float) parsed; + } } \ No newline at end of file -- 2.39.5