我想输入十进制数字,如“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());
}
}
});
Run Code Online (Sandbox Code Playgroud)
小智 5
@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());
}
}
Run Code Online (Sandbox Code Playgroud)
我使用空格而不是 $,它对我有用
| 归档时间: |
|
| 查看次数: |
591 次 |
| 最近记录: |