Java用逗号或点和两位小数值验证价格 [英] Java validate price with comma or dot and two decimal value
问题描述
验证字符串的最佳方法和解决方案是必须用点或逗号表示价格值并且最多有两个小数值?
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
还是别的什么?
这些价值被接受:
1
11
1,05
2,5
1.05
2.5
我看到这些解决方案但是这些并不是我想要的:
I see these solution but these are not exactly what I want:
我也试试这个RegExp / ^(\\d +(?:[\\.\\,] \\\\ {2})?)$ /
但它没有工作。
I also try this RegExp /^(\\d+(?:[\\.\\,]\\d{2})?)$/
but it doesn't work.
推荐答案
使用此规则ar表达式:
Use this regular expression:
final String regExp = "[0-9]+([,.][0-9]{1,2})?";
它匹配1位或更多位数,后跟可选:逗号或句号,后跟1或2数字。
It matches 1 or more digits, followed by optional: comma or full stop, followed by 1 or 2 digits.
在Java中你可以使用:
In Java you can use:
-
String.matches(String regex)
简单地验证String
。例如:1.05。匹配(regExp)
返回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();
这篇关于Java用逗号或点和两位小数值验证价格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!