我想输入十进制数字,如“23.50”,“250.75”。下面的代码提供了这个,但它在数字前面加上一个“$”符号,如“$ 23.50”,“$ 250.75”..我想删除美元符号并尝试了一些方法,但我不能。如何更改正则表达式并显示?
以下编号:
inputAmount.setRawInputType(Configuration.KEYBOARD_12KEY);
inputAmount.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
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,'$');
inputAmount.setText(cashAmountBuilder.toString());
// keeps the cursor always to the right
Selection.setSelection(inputAmount.getText(), cashAmountBuilder.toString().length());
}
}
});
答案 0 :(得分:4)
@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, ' ');
edAmountAddMoney.setText(cashAmountBuilder.toString());
// keeps the cursor always to the right
Selection.setSelection(edAmountAddMoney.getText(), cashAmountBuilder.toString().length());
}
}
我使用空格而不是$,它对我有用
答案 1 :(得分:0)
删除该行:
cashAmountBuilder.insert(0,'$');
从正则表达式中删除\\$
。