【发布时间】:2012-10-19 02:57:04
【问题描述】:
以下代码适用于我的生产应用程序中的所有手机,但运行 4.1.2 的 Galaxy Nexus 除外。 Play商店给我发了错误,我先贴代码,再贴错误:
// Roughly formats the currency by loping off the decimal places (amount
// comes already rounded)
public static String formatCurrencyRound(double amount) {
String currency = formatCurrency(amount); // Returns "$8.00"
return currency.substring(0, currency.indexOf("."));
}
错误:
java.lang.RuntimeException: Unable to resume activity {com.ootpapps.saving.made.simple/com.ootpapps.saving.made.simple.SavingsPlanOverview}: java.lang.StringIndexOutOfBoundsException: length=9; regionStart=0; regionLength=-1
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2575)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2603)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2089)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.StringIndexOutOfBoundsException: length=9; regionStart=0; regionLength=-1
at java.lang.String.startEndAndLength(String.java:593)
at java.lang.String.substring(String.java:1474)
at com.ootpapps.saving.made.simple.App.formatCurrencyRound(App.java:68)
at com.ootpapps.saving.made.simple.SavingsPlanOverview.updateSavingsPlanWidgets(SavingsPlanOverview.java:224)
at com.ootpapps.saving.made.simple.SavingsPlanOverview.onResume(SavingsPlanOverview.java:156)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1184)
at android.app.Activity.performResume(Activity.java:5082)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2565)
... 12 more
如果有人可以提出一种更好的方法来将此货币字符串舍入,或者将原始数字舍入为没有小数的格式化字符串,我将不胜感激。同样,由于某种原因,这仅在运行 4.1.2 的 GNexus 上失败。
谢谢!
编辑添加格式货币代码:
public static String formatCurrency(double amount) {
NumberFormat currency = NumberFormat.getCurrencyInstance();
return currency.format(amount);
}
继续编辑 - 我使用的代码可以将货币四舍五入到整美元:
public static String formatCurrencyWhole(double amount) {
NumberFormat currency = NumberFormat.getCurrencyInstance();
currency.setMaximumFractionDigits(0);
currency.setMinimumFractionDigits(0);
return currency.format(amount);
}
【问题讨论】:
-
如果你还想向下取整,你考虑过 Math.floor() 吗?
-
你能贴出formatCurrency(Double)的代码吗?
-
最终:我会使用 NumberFormat,只需将 FractionDigits 设置为 0 的 Max 和 Min。我当时不知道这种方法存在,对我来说似乎有点不正统,也许措辞“分数”而不是“小数”让我失望。无论如何,上面的设置器强制数字的小数为 0,因此,数字将始终是整数。
-
是的,但这些答案都不是,这是我在上面发布的。
标签: android exception currency rounding