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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With