Java’s NumberFormat Bug

I ran across this bug, when I had to verify that the Trinidad NumberConverter is able to parse currency strings for the France locale (fr_FR).
Why not, I thought…..

Here is a bit simple code:

String value = "12 345,68 €";
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.FRANCE);
ParsePosition pp = new ParsePosition(0);
Number n = (Number) nf.parse(value, pp);
System.out.println(n);

I’d expect that the System.out.println() prints a number (12345.68), but it is not the case!The problem is, that the currency string (“12 345,68 €”) contains two spaces, but for the fr_FR locale the parser wants this:

  • the thousands separator is non-breaking space
  • the space between the “number” and the EUR-symbol is a regular String

In the end, it means, that I have to create a parser, in order to use the Java build-in one🙂

A hack demonstrates, what the Java-parser expects, for France Locale (true for Finish as well):

String value = "12 345,68";
value = value.replace(' ', '\u00a0');
value += " €";
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.FRANCE);
ParsePosition pp = new ParsePosition(0);
Number n = (Number) nf.parse(value, pp);
System.out.println(n);

That finally prints out the expected number. Wouldn’t it be great, if the parser would accept a non-braking space in front of the €-symbol?

The bug is still open…

Howdy!

Posted in java
4 comments on “Java’s NumberFormat Bug
  1. Odi says:

    I wonder how a user is supposed to enter a nb space with an ordinary keyboard. I mean these formats are obiously meant for GUIs. But probably more for formatting (displaying data) than for parsing user input.

  2. matthiaswessendorf says:

    The JSF-NumberConverter uses these APIs internally to parse user-input, submitted via Browser. That makes the bug even worse, IMO

  3. matthiaswessendorf says:

    For sure,… this works

    String value = “12\u00a0345,68 €”;
    NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.FRANCE);
    ParsePosition pp = new ParsePosition(0);
    Number n = (Number) nf.parse(value, pp);
    System.out.println(n);

    Looks like I have to work around…

  4. Stephan Eggermont says:

    Euro parsing doesn’t work, period. See http://groups.google.com/group/jmatter/browse_thread/thread/5b26289f68f0e8bb
    Having a single currency area means the parser has to accept all euro locales separators and groupseparators.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: