Invalid double崩溃分析

第一次遇到java.lang.NumberFormatException: Invalid double: "0,3"这样包含逗号的浮点数异常,第一感觉就是服务器给的数据错误,但前段时间复现了这个异常,才发现是代码不规范导致了这样的异常:
崩溃的详细log如下:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.frank.lollipopdemo, PID: 10898
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.frank.lollipopdemo/com.frank.lollipopdemo.MainActivity}: java.lang.NumberFormatException: Invalid double: "0,3"
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
    at android.app.ActivityThread.access$800(ActivityThread.java:151)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5254)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
 Caused by: java.lang.NumberFormatException: Invalid double: "0,3"
    at java.lang.StringToReal.invalidReal(StringToReal.java:63)
    at java.lang.StringToReal.initialParse(StringToReal.java:164)
    at java.lang.StringToReal.parseDouble(StringToReal.java:282)
    at java.lang.Double.parseDouble(Double.java:301)
    at com.frank.lollipopdemo.MainActivity.onCreate(MainActivity.java:43)
    at android.app.Activity.performCreate(Activity.java:5990)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
    at android.app.ActivityThread.access$800(ActivityThread.java:151) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:135) 
    at android.app.ActivityThread.main(ActivityThread.java:5254) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:372) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 

而出错的代码类似这样的:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_content = (TextView) findViewById(R.id.tv_content);
        String jsonVal = "0.31415926";
        String title = remain1Places(jsonVal);// -> 0.3
        tv_title.setText(title);
        tv_content.setText(getPercent(Double.parseDouble(title)));// -> ##.##%
    }

    public static String remain1Places(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        return String.format("%.1f", Double.parseDouble(string));
    }

    public static String getPercent(double value) {
        NumberFormat numberFormat = NumberFormat.getPercentInstance();
        numberFormat.setMinimumFractionDigits(1);
        numberFormat.setMaximumFractionDigits(2);
        return numberFormat.format(value);
    }

想把浮点数”0.31415926”保留一位小数为0.3,就使用了String.format()方法完成,而且完全不顾第16行编译器对我们的建议:
这里写图片描述
之后,我们想把保留了一位小数后的浮点数”0.3”转成百分比的形式”30.0%”,当然先转成double,然后利用NumberFormat格式化成百分比。
看似没有问题,但是当我们把系统语言换成法语(France)之后,程序直接Crash,而且当我们只显示remain1Places()后的title时,发现”0.31415926”变成了”0,3”,而不是”0.3”,这就直接导致了Double.parseDouble(“0,3”)抛出一个数据格式异常。
那为什么String.format()会将小数点的”句点(.)“换成了”逗号(,)“呢?

摘自维基百科
A decimal mark is a symbol used to separate the integer part from the fractional part of a number written in decimal form.
Different countries officially designate different symbols for the decimal mark. The choice of symbol for the decimal mark also affects the choice of symbol for the thousands separator used in digit grouping, so the latter is also treated in this article.
这里写图片描述

可以看到,有很多地区(图中的绿色部分)都是用逗号(,)作为小数点的,如19,90€表示19点9欧元;但计算机程序中的浮点数必须用句点(.)作为小数点,如double price = 19.90;表示浮点数19点9。所以在使用double的包装类DoubleparseDouble(String)valueOf(String)方法将字符串表示的double值转成double时,字符串所表示的double值必须是用句点(.)分隔的浮点数,也就是计算机的浮点数表示形式。

Double.valueOf(String)方法仅仅调用了Double.parseDouble(String)并返回Double对象。
Double.parseDouble(String)方法返回原语类型的double变量。

因此,我们就可以断定这是一个本地化(Locale)的问题了。现在再来看一下编译器(lint)给我们String.format()方法的建议:

Implicitly using the default locale is a common source of bugs: Use String.format(Locale, …) instead.
隐式地使用默认的区域设置是常见Bug源,请使用String.format(Locale, …)等方法替换它。

也就是说,String.format(String format, Object... args)会调用format(Locale.getDefault(), format, args)使用用户默认的区域设置返回格式化好且本地化好的字符串,因用户设置的不同而返回不同的字符串,进而出现Bug。如果你只是想格式化字符串而不是人为干预,应该用String.format(Locale locale, String format, Object... args)方法,Locale参数用Locale.US就可以了。

因此,我们应该重视本地化问题:

  • 将字符串所有字符转为大/小写的方法String.toLowerCase()/String.toUpperCase()并不一定能将字符真正的大/小写(如区域设置为土耳其时,i大写后还是i),因此应该指定要使用的区域设置,因此应该使用String.toLowerCase(Locale locale)/String.toUpperCase(Locale locale)
  • 格式化字符串的方法String.format(String format, Object... args)应该指定区域设置,以避免区域设置变化导致的Bug。
  • 千万不要将数字format()成字符串后再将该字符串转回数字类型,因为format()后的字符串可能已经不是合法的原语类型的数字了。即永远不要出现类似这样Double.parseDouble(new DecimalFormat("#.##").format(doubleValue))的代码。如果一定要format后再转回数字,就必须做好本地化工作,指定具体的Locale。建议使用Locale.US以保证小数点始终是句点格式。
  • 建议使用NumberFormatDecimalFormat格式化数据,如:

     public static String remain1Places(String str) {
        NumberFormat numberFormat = NumberFormat.getInstance(Locale.getDefault());
        numberFormat.setMinimumFractionDigits(1);
        numberFormat.setMaximumFractionDigits(1);
        numberFormat.setGroupingUsed(false);
        return numberFormat.format(Double.parseDouble(str));
    }
    
    public static String getPercent(String str) {
        NumberFormat numberFormat = NumberFormat.getPercentInstance(Locale.getDefault());
        numberFormat.setMinimumFractionDigits(1);
        numberFormat.setMaximumFractionDigits(2);
        numberFormat.setGroupingUsed(false);
        return numberFormat.format(Double.parseDouble(str));
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值