2

How to format a number with a comma in TextField in compose.

Example: 1234567899 -> 123,456,789,9

humazed
  • 74,687
  • 32
  • 99
  • 138

1 Answers1

11

The best way to do this is with visualTransformation

example

@Composable
fun CurrencyTextField(
    onValueChange: (String) -> Unit,
) {
    var text by remember { mutableStateOf("") }

    BasicTextField(
        value = text,
        onValueChange = { newText: String ->
            if (newText.length <= Long.MAX_VALUE.toString().length && newText.isDigitsOnly()) {
                text = newText
                onValueChange(newText)
            }
        },
        keyboardOptions = KeyboardOptions.Default.copy(
            keyboardType = KeyboardType.Number,
        ),
        visualTransformation = NumberCommaTransformation(),
    )
}

// format long to 123,456,789,9
class NumberCommaTransformation : VisualTransformation {
    override fun filter(text: AnnotatedString): TransformedText {
        return TransformedText(
            text = AnnotatedString(text.text.toLongOrNull().formatWithComma()),
            offsetMapping = object : OffsetMapping {
                override fun originalToTransformed(offset: Int): Int {
                    return text.text.toLongOrNull().formatWithComma().length
                }

                override fun transformedToOriginal(offset: Int): Int {
                    return text.length
                }
            }
        )
    }
}

fun Long?.formatWithComma(): String =
    NumberFormat.getNumberInstance(Locale.US).format(this ?: 0)
humazed
  • 74,687
  • 32
  • 99
  • 138