Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumberFormat currency parsing failing "Unparseable number"

Tags:

java

currency

NumberFormat throws ParseException when I try to parse "10,10 €".

@Test
public void get_currency_from_text() throws Exception {
    String moneyAsString = "10,10 €";
    //Do not use double for monetary values
    Double moneyAsDouble = 10.10;

    NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.GERMANY);
    Double parsedMoney = formatter.parse(moneyAsString).doubleValue();
    assertEquals(moneyAsDouble, parsedMoney);
}

This is what I is thrown when I run the test

java.text.ParseException: Unparseable number: "10,10 €"

It works fine whenever I do this though:

@Test
public void get_currency_from_text() throws Exception {

    Double moneyAsDouble = 10.10;

    NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.GERMANY);
    String moneyAsString = formatter.format(moneyAsDouble);
    Double parsedMoney = formatter.parse(moneyAsString).doubleValue();

    System.out.println(moneyAsString);
    //10,10 €

    assertEquals(moneyAsDouble, parsedMoney);
}

I suspect that it has something to do with the space, but I still don't know how to fix it, any ideas?

like image 248
xgrimau Avatar asked Oct 17 '22 07:10

xgrimau


1 Answers

Seems like the space in "10,10 €" is not the right ASCII which the formatter is expecting. It's clearly mentioned here (Parse currency with symbol: Not all case working - Java) that The format class expect the char with code 160 which is describe as "Non-breaking space".

like image 168
Anuj Vishwakarma Avatar answered Nov 09 '22 23:11

Anuj Vishwakarma