简体   繁体   中英

How to add dot in between numbers using java

I need to validate customer entered input with java. ie we should allow numbers seven digits, after that if customer willing to enter numbers we should add '.' (dot) as separator.After separator we should allow only two digits, if any more digits enter we should throw an error.

Ex: 12345 --> Valid

Thanks,

You can use regular expressions for that:

private static final String PATTERN = "\\d{1,7}(\\.\\d{1,2})?";

public static void main(final String[] args) {
    final Pattern ptrn = Pattern.compile(PATTERN);
    System.out.println(ptrn.matcher("1").matches());
    System.out.println(ptrn.matcher("1234567").matches());
    System.out.println(ptrn.matcher("12345678").matches());
    System.out.println(ptrn.matcher("1234567.").matches());
    System.out.println(ptrn.matcher("1234567.1").matches());
    System.out.println(ptrn.matcher("1234567.12").matches());
    System.out.println(ptrn.matcher("1234567.123").matches());
    System.out.println(ptrn.matcher("1.12").matches());
    System.out.println(ptrn.matcher(".12").matches());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM