1

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?

Alexei Vinogradov
  • 1,548
  • 3
  • 15
  • 34

4 Answers4

2

Use a localized number format (or a regex if it's always in German format).

Regex could be something like ^(?:0|[1-9][0-9]{0,2}(?:\.[0-9]{3})*),[0-9]{2}$, with ^ and $ not being necessary when using String#matches() or Matcher#matches().

Number format could be a DecimalFormat like ###,##0.00 or just use NumberFormat.getInstance( Locale.GERMAN ). The problem with number formats, however, is that it allows a number to have leading zeros so if you want to disallow those you could check the first digit for being a zero or not.

Thomas
  • 87,414
  • 12
  • 119
  • 157
  • NumberFormat didn't work, as it allowed e.g. leading zeros RegExp should it be, I think, just looking for the right now. – Alexei Vinogradov Oct 01 '15 at 13:24
  • Looks like that ^(?:0|[1-9]\d{0,2}(?:\.\d{3})*),\d{2}$ does the trick – Alexei Vinogradov Oct 01 '15 at 13:33
  • 1
    @AlexeiVinogradov yes, that seems to be ok (I'll add that `0,xx` case to the answer for others to spot). Just note that `\d` would allow foreign digits as well so you might want to use `[0-9]` instead. – Thomas Oct 01 '15 at 13:35
0

Maybe the Apache CurrencyValidator is what you are looking for.

public static void main (String[] args) throws java.lang.Exception {
     BigDecimalValidator validator = CurrencyValidator.getInstance();

     BigDecimal amount = validator.validate("€ 123,00", Locale.GERMAN);

     if(amount == null){
         System.out.println("Invalid amount/currency.");
     }

}
SWoeste
  • 1,137
  • 9
  • 20
0

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");
smilyface
  • 5,021
  • 8
  • 41
  • 57
Alexei Vinogradov
  • 1,548
  • 3
  • 15
  • 34
0

Use the following Pattern: "([0-9]{1,3}\.)*[0-9]{1,3}\,[0-9]{2}"

System.out.println("11.118.576.587,58".matches("([0-9]{1,3}\\.)*[0-9]{1,3}\\,[0-9]{2}"));
J. Jerez
  • 704
  • 8
  • 6