Android的资金投入固定小数 [英] Android Money Input with fixed decimal
本文介绍了Android的资金投入固定小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你如何创建格式输入只剩下钱的格式一个EditText项?当用户输入5,我想输入看起来像$ 0.05而当他们再进入3,输入应该像$ 0.53,最后他们进入6和输入应该类似于$ 5.36。
How do you create an edittext entry that formats input in money format only? When the user enters 5, I want the input to look like "$0.05" and when they then enter 3, the input should now look like "$0.53" and finally they enter 6 and the input should look like "$5.36".
推荐答案
ninjasense的完整的解决方案基本的工作原理,但它有一些问题:
ninjasense's complete solution basically works, but it has some issues:
- 每次字段的数据被修改,在onTextChanged处理程序,光标位置复位为0指数在球场上,这是一个有点恼人的货币价值打字的时候发生的。
- 在它使用花车格式化货币值,这可能会适得其反。
对于第一个问题,我没有解决方案,然而,对于第二个code是这样工作的:
For the first problem I don't have solution yet, for the second one code like this works:
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if(!s.toString().matches("^\\$(\\d{1,3}(\\,\\d{3})*|(\\d+))(\\.\\d{2})?$"))
{
String userInput= ""+s.toString().replaceAll("[^\\d]", "");
StringBuilder cashAmountBuilder = new StringBuilder(userInput);
while (cashAmountBuilder.length() > 3 && cashAmountBuilder.charAt(0) == '0') {
cashAmountBuilder.deleteCharAt(0);
}
while (cashAmountBuilder.length() < 3) {
cashAmountBuilder.insert(0, '0');
}
cashAmountBuilder.insert(cashAmountBuilder.length()-2, '.');
cashAmountBuilder.insert(0, '$');
cashAmountEdit.setText(cashAmountBuilder.toString());
}
}
这篇关于Android的资金投入固定小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文