javacurrencycurrency-formatting

How to validate the Currency String in java


Suppose I have a currency String in German format:

String money="1.203.432,25";

I want to check if money is a valid currency value. "0,00" is valid, "134.20,24" is invalid, "02,23" is invalid and so on. How can I do it in Java?


Solution

  • This snippet seems to work:

    String money="23.234,00";
    Pattern p=Pattern.compile("^(?:0|[1-9]\\d{0,2}(?:\\.\\d{3})*),\\d{2}$");
    Matcher m=p.matcher(money);
    if (m.matches()) System.out.println("valid");
    else System.out.println("invalid");