我想創建一個Eddittext來從左到右輸入2位小數的貨幣值。如果there's沒有價值它顯示0.00,並在用戶鍵入文本應該改變acording這些規則: 帶有固定小數的Android反轉貨幣輸入
從來就試圖得到它使用TextWatcher做過這樣類似的問題,但我不能把它做因爲它在更新文本後不斷調用TextWatcher。
我想創建一個Eddittext來從左到右輸入2位小數的貨幣值。如果there's沒有價值它顯示0.00,並在用戶鍵入文本應該改變acording這些規則: 帶有固定小數的Android反轉貨幣輸入
從來就試圖得到它使用TextWatcher做過這樣類似的問題,但我不能把它做因爲它在更新文本後不斷調用TextWatcher。
我終於得到它只是工作,我想用TextWatcher與此代碼,希望它可以幫助別人:
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if ((count - before) > 0) {
String text = s.toString().replace(',', '.');
text = text.replace("..", ".");
if (text.equals(".")) {
text = "0,00";
amount_field.setText(text);
amount_field.setSelection(2);
} else {
int counter = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == '.') {
counter++;
if (counter > 1) {
break;
}
}
}
if (counter > 1) {
StringBuilder sb = new StringBuilder(text);
sb.deleteCharAt(start);
amount_field.setText(sb.toString().replace('.', ','));
amount_field.setSelection(start);
} else {
Float value = Float.valueOf(text);
String result = String.format("%.2f", value);
amount_field.setText(result.replace('.', ','));
if (start != result.length()) {
amount_field.setSelection(start + 1);
} else {
amount_field.setSelection(start);
}
}
}
}
}
試試這個:
String yourStringToPutIntoTextView = String.format("%.2f", YourFloat);
下面的例子:
List<Float> listTestValue = new ArrayList<Float>();
listTestValue.add(new Float(10));
listTestValue.add(new Float(10.10));
listTestValue.add(new Float(1010));
listTestValue.add(new Float(0));
listTestValue.add(new Float(0.9));
listTestValue.add(new Float(.12));
listTestValue.add(new Float(0.01));
for(Float f : listTestValue)
{
String s = String.format("%.2f", f);
System.out.println(s);
}
如果你有noInput格式字符串爲f = 0,這樣的:
String noInput = String.format("%.2f", (float)0);
注意,值必須是Float!
輸出:
10,00
10,10
1010,00
0,00
0,90
0,12
0,01
你想要的輸出做什麼? – Sangeeta
我更新了我的問題,明確表明它的Edittext,並且我希望文本可以在用戶輸入時進行格式化。 – IBueno
好的..我得到你的問題將很快發佈我的答案。 – Sangeeta