在这里,我必须显示货币小数分隔符和千位分隔符,根据给定的输入,如:
private var decimalSeparator: Char = '.'
private var thousandSeparator: String = ","
fun setDecimalSeparator(decimalSeparator: Char) {
this.decimalSeparator = decimalSeparator
}
fun setThousandSeparator(thousandSeparator: String) {
this.thousandSeparator = thousandSeparator
}
我还为编辑文本字段添加了文本监视器,以便在Add comma as thousands separator for numbers in EditText for Android Studio?的帮助下添加相应的小数点和千位分隔符,如下所示
field.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(p0: Editable?) {
Log.d("CharCount:", p0.toString().length.toString())
field.removeTextChangedListener(this)
try {
var givenstring: String = p0.toString()
if (givenstring.contains(thousandSeparator)) {
givenstring = givenstring.replace(thousandSeparator.toRegex(), "")
}
val longVal: Long = givenstring.toLong()
val formatter = DecimalFormat("#$thousandSeparator###$thousandSeparator###")
val formattedString = formatter.format(longVal)
field.setText(formattedString)
field.setSelection(field.text.length)
// to place the cursor at the end of text
} catch (nfe: NumberFormatException) {
nfe.printStackTrace()
} catch (e: Exception) {
e.printStackTrace()
}
field.addTextChangedListener(this)
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
// no need any callback for this.
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
// no need any callback for this.
}
})
当thousandSeparator为句点(.)时,此选项不起作用;有谁能帮我一下吗?先谢谢了
1条答案
按热度按时间vd2z7a6w1#
这就是它的工作原理。我从https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html那里得到了帮助
Add comma as thousands separator for numbers in EditText for Android Studio?