From a2c2285cc3636fabe3856989446a1c47df328dfe Mon Sep 17 00:00:00 2001 From: Claudio Paccone Date: Mon, 29 May 2017 18:44:40 +0200 Subject: [PATCH] =?UTF-8?q?Add=20convenience=20method=20to=20get=20formatt?= =?UTF-8?q?ed=20value=20from=20=E2=80=98FieldValue=E2=80=99=20(#27)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add convenience method to get formatted value from ‘FieldValue’ * Add ‘InvalidFieldValueException’ * Fix ‘formatNumberGrouping’ extension function * Add extension functions for unformatted number value --- src/main/kotlin/it/facile/form/Exceptions.kt | 5 +++++ .../it/facile/form/ui/utils/FormatterUtil.kt | 20 ++++++++++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 src/main/kotlin/it/facile/form/Exceptions.kt diff --git a/src/main/kotlin/it/facile/form/Exceptions.kt b/src/main/kotlin/it/facile/form/Exceptions.kt new file mode 100644 index 0000000..ae40097 --- /dev/null +++ b/src/main/kotlin/it/facile/form/Exceptions.kt @@ -0,0 +1,5 @@ +package it.facile.form + +import it.facile.form.storage.FieldValue + +class InvalidFieldValueException(fieldValue: FieldValue, override val message: String?) : Exception("Invalid FieldValue: $fieldValue") \ No newline at end of file diff --git a/src/main/kotlin/it/facile/form/ui/utils/FormatterUtil.kt b/src/main/kotlin/it/facile/form/ui/utils/FormatterUtil.kt index 3b20374..75669f7 100644 --- a/src/main/kotlin/it/facile/form/ui/utils/FormatterUtil.kt +++ b/src/main/kotlin/it/facile/form/ui/utils/FormatterUtil.kt @@ -1,5 +1,6 @@ package it.facile.form.ui.utils +import it.facile.form.storage.FieldValue import java.text.DecimalFormat import java.text.DecimalFormatSymbols import java.text.ParseException @@ -20,4 +21,21 @@ fun String.formatNumberGrouping(separator: Char): String { } return decimalFormat.format(number) -} \ No newline at end of file +} + +fun FieldValue.Text.formatNumberGrouping(separator: Char) = text.formatNumberGrouping(separator) + +fun String.getUnformattedNumberWithGrouping(separator: Char): Number? { + val symbols = DecimalFormatSymbols(Locale.ITALY).apply { groupingSeparator = separator } + val decimalFormat = DecimalFormat("###,###.###", symbols) + + val stringWithoutSeparator = this.replace(separator.toString(), "") + + return try { + decimalFormat.parse(stringWithoutSeparator) + } catch (pe: ParseException) { + return null + } +} + +fun FieldValue.Text.getUnformattedNumberWithGrouping(separator: Char) = text.getUnformattedNumberWithGrouping(separator)