如何解决国际化的数字格式
我正在尝试将我的应用在 Android 上国际化。 我知道在欧洲以及世界其他地方小数和数字的表示方式与美国不同
我正在尝试使用 NumberFormat 来帮助我更改代表欧洲小数的字符串输入。 因此,例如:
- String number1 = "8,765" 应该变成 "8.77" 格式化后 数字格式
- String number2 = "1.203" 用 NumberFormat 格式化后应该变成 "1,203"
- String number3 = "1.203,5632" 用 NumberFormat 格式化后应该变成 "1,203.56"
我的代码几乎可以完美运行,但我遗漏了一些东西: 我不想使用 String.format 方法。 我想使用 NumberFormat。
NumberFormat nformat = NumberFormat.getInstance(Locale.US);
nformat.setMaximumFractionDigits(2);
nformat.setMaximumFractionDigits(2);
String user_string = "8,747";
try{
Number my_number = nformat.parse(user_string);
String result = nformat.format(my_number);
System.out.println("look at result: " + result); //this prints: 8,747.00 NOT 8.75
}catch(Exception exception){
}
如何让 NumberFormat 打印 8.75 而不是 8,747.00 。另外,我可以在 user_string 上使用 replace OR replaceAll 调用但我不想使用额外的计算。 NumberFormat 如何处理这个问题?
谢谢
解决方法
在回答你的问题之前,我想告诉你不要吞下异常。一个空的 catch 块是一个糟糕的禁忌。编辑:当异常发生时,你将不知道你的程序出了什么问题。这就像蒙着眼睛编码。链接到底部的简短文章更详细地解释了这种做法如何违背了例外的目的。
要将一种字符串格式转换为另一种字符串格式,您需要两个格式化程序,一个用于解析,一个用于格式化。
NumberFormat europeanInputFormat = NumberFormat.getInstance(Locale.GERMAN);
NumberFormat nformat = NumberFormat.getInstance(Locale.US);
nformat.setMaximumFractionDigits(2);
String user_string = "8,747";
try {
Number my_number = europeanInputFormat.parse(user_string);
String result = nformat.format(my_number);
System.out.println("look at result: " + result); // this prints: 8.75
} catch (ParseException | IllegalArgumentException e) {
e.printStackTrace();
}
输出:
看结果:8.75
并非所有欧洲国家/地区都使用相同的格式。我首先使用了 Locale.FRENCH
。这不起作用,因为法语格式使用空格而不是点作为千位分隔符。
链接
Wikipedia article on Error hiding,error swallowing or exception swallowing
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。