【发布时间】:2015-04-08 09:28:42
【问题描述】:
在 Android 应用程序中,我有一个字段,用户应在其中输入一些 14 位数字,例如 12345678901234。 我希望这个号码看起来像 12 3456 7890 1234。 我试图通过代码来做到这一点:
if((s.length() == 2 || s.length() == 7 || s.length() == 12)){
s.insert(s.length(), " ");
}
但是当用户开始在文本中间输入时,我的代码会出错。
我尝试使用 DecimalFormat 类:
DecimalFormat decimalFormat = new DecimalFormat("##,####.#### ####");
String formattedText = decimalFormat.format(Double.parseDouble(etContent.getText().toString()));
但我收到 IllegalArgumentException。
任何想法如何做到这一点?
P.S 主要问题是我应该“立即”格式化文本,例如:
1
12
12 3
12 34
12 345
12 3456
12 3456 7
12 3456 78
12 3456 789
12 3456 7890
12 3456 7890 1
12 3456 7890 12
12 3456 7890 123
12 3456 7890 1234
【问题讨论】:
-
关于哪个参数的 IllegalArgumentException?
-
new DecimalFormat("##,####.#### ####")
-
那一行不会给..可能是第二行可以给\
-
你应该考虑做屏蔽输入stackoverflow.com/questions/2912375/…
-
decimalFormat.format(Double.parseDouble("12345678901234")) 应该可以工作。它会给你逗号分隔的值,你可以用空格替换。
标签: java android string-formatting number-formatting decimalformat