Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java validate price with comma or dot and two decimal value [closed]

Tags:

java

regex

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.

like image 455
lory105 Avatar asked Jun 08 '26 21:06

lory105


1 Answers

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.

like image 130
Adam Stelmaszczyk Avatar answered Jun 11 '26 12:06

Adam Stelmaszczyk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!