Java validate price with comma or dot and two decimal value

java, regex

Solution

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.

Problem

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.

Original source

Related problems