Java用逗号或点和两位小数值验证价格 [英] Java validate price with comma or dot and two decimal value

查看:116
本文介绍了Java用逗号或点和两位小数值验证价格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

验证字符串的最佳方法和解决方案是必须用点或逗号表示价格值并且最多有两个小数值?

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:

java十进制字符串格式

在jtextfield中对'价格'进行评估

我也试试这个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:

模式匹配,这将是快速 更多经常使用正则表达式。示例:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆