Java 十进制格式解析问题 [英] Java Decimal Format parsing issue
问题描述
public class NumFormatTest
{
public static void main(String[] args) throws ParseException
{
String num = "1 201";
DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.FRANCE);
System.out.println("Number Before parse: "+num);
double dm = df.parse(num).doubleValue();
System.out.println("Number After parse: "+dm);
}
}
输出:
Number Before parse: 1 201
Number After parse: 1.0
预期输出:
Number Before parse: 1 201
Number After parse: **1201**
谁能帮我理解为什么 parse 无法将 FRENCH 语言环境格式的字符串 (1 201) 转换为正常的双精度值 (1201.0)?
Can any please help me understand why parse is not able to convert a FRENCH locale formatted string (1 201) to normal double value (1201.0)?
推荐答案
有两种空格.正常"空格字符(No. 32 - HEX 0x20)和不间断空格(NBSP)(No. 160 - HEX 0xA0).
There are two kinds of spaces. The "normal" space character (No. 32 - HEX 0x20) and the non-breaking space (NBSP) (No. 160 - HEX 0xA0).
法语语言环境要求数字之间的空白字符是不间断空格!你可以用这行代码来帮助自己:
The French locale expects the whitespace character between the digits to be the non breaking space! You can help yourself with this line of code:
String num = "1 201";
num = num.replaceAll(" ", "\u00A0"); // '\u00A0' is the non breaking whitespace character!
这样你的代码就会像预期的那样工作.请注意,如果您将 double
格式化为具有法语语言环境的 String
,则生成的空白字符也将是 NBSP!!!
This way your code will work like expected. Please note that if you format a double
into a String
with French locale the resulting whitespace character will be the NBSP too!!!
DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.FRENCH);
System.out.println(df.format(1201.1));
// This will print "1 202,1" But the space character will be '\u00A0'!
这篇关于Java 十进制格式解析问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!