简体   繁体   中英

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?

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.

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.");
     }

}

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("unvalid");

使用以下模式:“([[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}"));

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