private boolean validateSno(double inSno) {
//sno is the serial number
int firstThree=(int)inSno;
double secondThree=(inSno-firstThree)*1000;
boolean same=false;
double checkDigit=inSno*1000-(int)inSno;
if(checkDigit>0.0)
{
same=false;
}
else
{
if(firstThree>=100&&firstThree<=300)
{
if(secondThree>=001&&secondThree<=999)
{
same=true;
}
}
}
return same;
}
我需要的结果是XXX.YYY形式,但因为它是一个实数我不知道如何分割前3个数字和后3个数字。每个都有自己的验证要求
有没有一种简单的方法使用mod / div或?
例如,编号456.234
double number = 456.234;
double firstThree = (int)number; \\ output 456
double lastThree = (number * 1000 % 1000); \\ output 234
您可以考虑使用字符串和stringtokenizer类。
这是一个棘手的方式,但并不是那么糟糕。
import java.util.StringTokenizer;
public class TestAnyParser {
public static void main(String[] args)
{
validateSno(456.234);
}
private static boolean validateSno(double inSno) {
boolean isReal = false;
String sInSno = String.valueOf(inSno);
StringTokenizer stTok = new StringTokenizer(sInSno, ".");
isReal = stTok.countTokens() == 2;
if(isReal)
{
int realpart = Integer.parseInt(stTok.nextToken());
int imgpart = Integer.parseInt(stTok.nextToken());
System.out.println(realpart + ": " + imgpart);
}
else
{
//do something part.
}
return true;
}
}
以下使用带有正则表达式的字符串验证来检查数字是否是正确的长度和正确的范围
private boolean validateSno(double inSno) {
String serial = String.valueOf(inSno);
return serial.matches("[1-3]\\d{2}\\.[1-9][\\d]{2}\\d*");
}
注意最后的额外\\d*"
,这也是批准像123.45600000001这样的值