I am trying to implement visual transformation for price in format "##,##,###", main problem I am facing is when I parse the string using DecimalFormat if the first character is 0 and then user is entering a different number application is getting crashed as the offset being returned from overridden function is out of bounds from that of array as 0 is removed by decimal format. Below is the code for implementation. I am trying to resolve this only in case of first character entered as 0. One workaround to the problem i think is converting string to number in onValueChange and then convert it into string, but it doesnt seems a good solution, looking for other solutions.
class PriceTransformation(private val prefix: String = "₹ ") : VisualTransformation {
override fun filter(text: AnnotatedString): TransformedText {
var specialCharsCount = 0
var leadingZeroCount = 0
val zerosIndex = mutableListOf<Int>()
val originalToTransformed = mutableListOf<Int>()
val transformedToOriginal = mutableListOf<Int>()
val output = prefix + text.text.toBigDecimal().formattedPrice()
output.forEachIndexed { index, char ->
if (output[index] == "₹".single() || output[index] == " ".single() || output[index] == ",".single()) {
specialCharsCount++
} else {
originalToTransformed.add(index)
}
transformedToOriginal.add(index - specialCharsCount)
}
originalToTransformed.add(originalToTransformed.maxOrNull()?.plus(1) ?: 0)
transformedToOriginal.add(transformedToOriginal.maxOrNull()?.plus(1) ?: 0)
val offsetMapping = object : OffsetMapping {
override fun originalToTransformed(offset: Int): Int {
return originalToTransformed[offset]
}
override fun transformedToOriginal(offset: Int): Int {
return transformedToOriginal[offset]
}
}
return TransformedText(
text = AnnotatedString(output),
offsetMapping = offsetMapping
)
}
}