Invalid double崩溃分析

第一次遇到

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

E/AndroidRuntime: FATAL EXCEPTION: mainProcess: com.frank.lollipopdemo, PID: 
10898java.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”保留一位小数,就使用了String.format()
方法完成,而且完全不顾编译器对我们的建议:

这里写图片描述
之后,我们想把保留了一位小数后的浮点数”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的包装类Double
的parseDouble(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))
的代码。
建议使用NumberFormat
,如:

public static String remain1Places(String str) {
    NumberFormat numberFormat = NumberFormat.getInstance(Locale.getDefault());
    numberFormat.setMinimumFractionDigits(1);
    numberFormat.setMaximumFractionDigits(1);
    return numberFormat.format(Double.parseDouble(str));
}

public static String getPercent(String str) {
    NumberFormat numberFormat = NumberFormat.getPercentInstance(Locale.getDefault());
    numberFormat.setMinimumFractionDigits(1);
    numberFormat.setMaximumFractionDigits(2);
    return numberFormat.format(Double.parseDouble(str));
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,196评论 19 139
  • 1.在C/C++中实现本地方法 生成C/C++头文件之后,你就需要写头文件对应的本地方法。注意:所有的本地方法的第...
    JayQiu阅读 7,116评论 0 3
  • 在JavaSe5中,推出了C语言中printf()风格的格式化输出。这不仅使得控制输出的代码更加简单,同时也给与J...
    三藏君阅读 4,202评论 0 0
  • “你要是还要脸 就不要再见他” ...
    文艺胖猫阅读 3,265评论 0 1
  • 我在路这边 静静地等着 以为你会把我寻找 然...
    一苇可航阅读 2,540评论 0 1

友情链接更多精彩内容