如何解决将数字字符串格式化为2个十进制双精度数字,与数字字符串长度无关
在使用Kotlin开发的Android应用程序中,有一个EditText
仅接受视为美元的数字。输入的格式必须设置为2位小数,以便输入的格式如下所示:
- 7-> 0.07
- 73-> 0.73
- 736-> 7.36
尝试使用输入过滤器。输入过滤器还用于限制最大值和单个十进制输入项。
editTextField.filters =
arrayOf(DecimalInputFilter())
class DecimalDigitsInputFilter() : InputFilter {
override fun filter(
source: CharSequence?,start: Int,end: Int,dest: Spanned?,dstart: Int,dend: Int
): CharSequence? {}
}
无法获取格式化的数字。能够根据规则限制输入。
editTextField.addTextChangedListener(object : TextWatcher{
override fun beforeTextChanged(s: CharSequence?,count: Int,after: Int) {
print("beforeTextChanged")
}
override fun onTextChanged(s: CharSequence?,before: Int,count: Int) {
print("onTextChanged")
val inputFormatter = DecimalFormat("0.00")
inputFormatter.isDecimalSeparatorAlwaysShown = true
inputFormatter.minimumFractionDigits = 2
editTextField.setText((s.toString()).format(inputFormatter))
}
override fun afterTextChanged(s: Editable?) {
print("afterTextChanged")
}
})
这也失败。
解决方法
我认为主要的问题是您正在EditText
内的TextWatcher
内设置文本,这会导致循环递归,然后导致堆栈溢出。您应该更改在删除并再次添加TextWatcher
中包裹的文本。这是一个简单的解决方案:
editTextField.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?,start: Int,count: Int,after: Int) {
print("beforeTextChanged")
}
override fun onTextChanged(s: CharSequence?,before: Int,count: Int) {
print("onTextChanged")
val newValue = s.toString()
.takeIf { it.isNotBlank() }
?.replace(".","")
?.toDouble() ?: 0.0
editTextField.let {
it.removeTextChangedListener(this)
it.setText(String.format("%.2f",newValue / 100))
it.setSelection(it.text?.length ?: 0)
it.addTextChangedListener(this)
}
}
override fun afterTextChanged(s: Editable?) {
print("afterTextChanged")
}
})
,
对于Kotlin
fun roundOffDecimal(number: Double): String? {
val df = DecimalFormat("#,###,###.##")
df.roundingMode = RoundingMode.CEILING
return df.format(number)
}
RoundingMode.CEILNG或RoundingMode.FLOOR用于四舍五入最后一位数字。
#,###.##
根据所需的位值类型和所需的小数位数定制此部分。
上面的代码将显示与 3,250,250.12
类似的结果版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。