用逗号作为小数点分隔符来 parseDouble 的最佳方法? [英] Best way to parseDouble with comma as decimal separator?

查看:27
本文介绍了用逗号作为小数点分隔符来 parseDouble 的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为 逗号 用作 十进制分隔符,这段代码抛出一个 NumberFormatException:

Because of the comma used as the decimal separator, this code throws a NumberFormatException:

String p="1,234";
Double d=Double.valueOf(p); 
System.out.println(d);

是否有更好的方法来解析 "1,234" 以获得 1.234 比:p = p.replaceAll(",",";.");?

Is there a better way to parse "1,234" to get 1.234 than: p = p.replaceAll(",",".");?

推荐答案

使用 java.text.NumberFormat:

NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("1,234");
double d = number.doubleValue();

更新:

要支持多语言应用程序,请使用:

To support multi-language apps use:

NumberFormat format = NumberFormat.getInstance(Locale.getDefault());

这篇关于用逗号作为小数点分隔符来 parseDouble 的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆