3

What is the best way and the solution to validate a string that must represents a price value with dot or comma and with maximum two decimal values?

RegExp, java.text.DecimalFormat or something else?

These values are accepted:

1
11

1,05
2,5

1.05
2.5

I see these solution but these are not exactly what I want:

java decimal String format

valdating a 'price' in a jtextfield

I also try this RegExp /^(\\d+(?:[\\.\\,]\\d{2})?)$/ but it doesn't work.

Community
  • 1
  • 1
lory105
  • 6,112
  • 4
  • 31
  • 40

2 Answers2

18

Use this regular expression:

final String regExp = "[0-9]+([,.][0-9]{1,2})?";

It matches 1 or more digits, followed by optional: comma or full stop, followed by 1 or 2 digits.

In Java you can use:

  • String.matches(String regex) to simply validate a String. For example: "1.05".matches(regExp) returns true.

  • Pattern and Matcher, which will be faster the more often you use your regular expression. Example:

    final Pattern pattern = Pattern.compile(regExp);
    
    // This can be repeated in a loop with different inputs:
    Matcher matcher = pattern.matcher(input); 
    matcher.matches();
    

Test.

Community
  • 1
  • 1
Adam Stelmaszczyk
  • 19,665
  • 4
  • 70
  • 110
  • 3
    This whole regex doesn't make sense. – HamZa Jul 23 '13 at 09:15
  • This is the perfect way i supose, thanks for the info, sometimes i lost in validations too. – Distopic Jul 23 '13 at 09:16
  • 1
    Let me clarify, the OP asked to limit the *decimal* digits to 2 while this one matches infinite decimal digits. Also you're using a character class, so you don't need to escape the dot, and you don't need to use that ugly `|` otherwise you will also match a pipe. Try `12|1212` it will get matched, not really what the OP wanted. – HamZa Jul 23 '13 at 09:19
  • 1
    There are quite some failures here: [] specifies characters, | does not work here. And he wanted two decimal characters. Your regex allows *. The whole regex has to be "turned around". – Marc von Renteln Jul 23 '13 at 09:21
  • Now this will work. Thanks for the edit. – Marc von Renteln Jul 23 '13 at 09:29
  • @HamZa You are right, thank you. English is not my native language and my understanding of _decimal digits_ was wrong. I've improved the answer. – Adam Stelmaszczyk Jul 23 '13 at 09:31
  • @AdamStelmaszczyk English isn't my native language either +1 :) – HamZa Jul 23 '13 at 09:35
  • I tested the RegExp "[0-9]+([,.][0-9]{1,2})?" and it works, expected with inputs that start with "," or "." – lory105 Jul 23 '13 at 10:02
0

You can try some thing like this

 String str="1,05";
    String[] dotSub=str.split("\\.|,");
    if(dotSub.length==2){
         if(dotSub[1].length()<=2){
             System.out.println("valid price");
         }
         else{
             System.out.println("not a valid price");
         }
    }
    else{
        System.out.println("not a valid price");
    }
}
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115