首先,我知道双打并不是最好的货币,但在这种情况下,精度并不是非常重要。因此,我在 Play 商店中有一个实时应用程序,我发现欧元货币存在问题。出于某种原因,如果使用欧元本地化(无法使用 ADB 本地化重现),用户可以在 numberDecimal EditText 中输入逗号来分隔美元和美分。因此,当您期望从北美的用户那里获得“1000.00”时,您可能会从挪威的某个用户那里获得“1000,00”。
话虽这么说,numberDecimal 这样本地化并允许逗号是典型的吗?如果是这样,你知道它是否限制用户只插入最后一个逗号?我正在使用以下代码来解决此问题,如您所见,它依赖于它们只是一个逗号来替换:
// Required to handle European use of commas instead of decimals places
// in their currency.
edittext_amount.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable edittext_amount) {
String amount = "";
if (edittext_amount != null) {
try {
amount = edittext_amount.toString().replace(",", ".");
double_edittext_amount = Double.parseDouble(amount);
}
catch (NumberFormatException e) {
// Error
}
}
}
如前所述,上述代码是为了防止逗号产生错误,我收到的错误如下:
java.lang.NumberFormatException: Invalid double: "1000,00"
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseDouble(StringToReal.java:269)
at java.lang.Double.parseDouble(Double.java:295)
at java.lang.Double.valueOf(Double.java:332)
at com.ootpapps.saving.made.simple.SavingsPlanEditor.validateSavingsPlan(SavingsPlanEditor.java:233)
at com.ootpapps.saving.made.simple.SavingsPlanEditor.access$1(SavingsPlanEditor.java:217)
at com.ootpapps.saving.made.simple.SavingsPlanEditor$2.onClick(SavingsPlanEditor.java:109)
at android.view.View.performClick(View.java:3644)
at android.view.View$PerformClick.run(View.java:14313)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4517)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
at dalvik.system.NativeStart.main(Native Method)
感谢您的洞察力,我希望一劳永逸地解决这个问题!
编辑 - 将代码更改为使用 NumberFormat,如下所示:
// Required to handle European use of commas instead of decimals places
// in their currency.
edittext_amount.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable edittext_amount) {
String amount = "";
if (edittext_amount != null) {
try {
amount = edittext_amount.toString();
NumberFormat number_format = NumberFormat.getNumberInstance();
double_edittext_amount = number_format.parse(amount).doubleValue();
}
catch (NumberFormatException e) {
// Error
}
catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}