Skip to content

Commit

Permalink
Add convenience method to get formatted value from ‘FieldValue’ (#27)
Browse files Browse the repository at this point in the history
* Add convenience method to get formatted value from ‘FieldValue’

* Add ‘InvalidFieldValueException’

* Fix ‘formatNumberGrouping’ extension function

* Add extension functions for unformatted number value
  • Loading branch information
claudiopaccone authored and brescia123 committed May 29, 2017
1 parent 61d3cd4 commit a2c2285
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
5 changes: 5 additions & 0 deletions src/main/kotlin/it/facile/form/Exceptions.kt
Original file line number Diff line number Diff line change
@@ -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")
20 changes: 19 additions & 1 deletion src/main/kotlin/it/facile/form/ui/utils/FormatterUtil.kt
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -20,4 +21,21 @@ fun String.formatNumberGrouping(separator: Char): String {
}

return decimalFormat.format(number)
}
}

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)

0 comments on commit a2c2285

Please sign in to comment.