简体   繁体   中英

Numberformat.parse not working correctly for french locale in java

In my code, I am getting the locale value and using it in the below snippet of code :

    NumberFormat nf = NumberFormat.getInstance(locale);
    double value = nf.parse(input).doubleValue();

For en_gb locale and fr_fr locale the input provided is the same ie, 1,000.00. But the "value" is 1000.0 for en_gb locale and 1.0 for fr_fr locale.

Did try to search for solutions in the below posts : 1] NumberFormat.parse() does not work for FRANCE Locale space as thousand seperator 2] http://bugs.java.com/view_bug.do?bug_id=6318800

but no luck. Any thoughts/pointers on this will be really helpful.

You're parsing a string, which is '1,000.00'. The problem is, in France locale, the correct format of number 1000 is '1 000'. That's why you ended up getting an output of '1'.

An simple example is:

NumberFormat nf = NumberFormat.getInstance(Locale.FRANCE);

double d = 1000.00;
System.out.println(nf.format(d));

NumberFormat nf1 = NumberFormat.getInstance(Locale.UK);

System.out.println(nf1.format(d));

The output for France is '1 000' whereas for UK it's '1,000', which means in France, they use space(note its not the same space we can specify by ' ') instead of comma to separate thousand.

In your case, since the input is a string representation of a number, which is '1,000.00', this means it's locale specific and you need to use a right locale format to parse it. This implies that your application should be aware of it's locale from the context. Usually the NumberFormat class will just use the default locale, depending on where you run this application and for most cases, that's sufficient.

You do need to provide more detail on what you trying to do and why you're receiving a string as an input.

UPDATE

try this:

DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(Locale.UK);
DecimalFormat decimalFormat = new DecimalFormat();
decimalFormat.setDecimalFormatSymbols(dfs);

System.out.println(decimalFormat.parse("1,000"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM