How to check if a String is numeric in Java

前端 未结 30 2599
盖世英雄少女心
盖世英雄少女心 2020-11-21 05:26

How would you check if a String was a number before parsing it?

30条回答
  •  感情败类
    2020-11-21 06:04

    I have illustrated some conditions to check numbers and decimals without using any API,

    Check Fix Length 1 digit number

    Character.isDigit(char)
    

    Check Fix Length number (Assume length is 6)

    String number = "132452";
    if(number.matches("([0-9]{6})"))
    System.out.println("6 digits number identified");
    

    Check Varying Length number between (Assume 4 to 6 length)

    //  {n,m}  n <= length <= m
    String number = "132452";
    if(number.matches("([0-9]{4,6})"))
    System.out.println("Number Identified between 4 to 6 length");
    
    String number = "132";
    if(!number.matches("([0-9]{4,6})"))
    System.out.println("Number not in length range or different format");
    

    Check Varying Length decimal number between (Assume 4 to 7 length)

    //  It will not count the '.' (Period) in length
    String decimal = "132.45";
    if(decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
    System.out.println("Numbers Identified between 4 to 7");
    
    String decimal = "1.12";
    if(decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
    System.out.println("Numbers Identified between 4 to 7");
    
    String decimal = "1234";
    if(decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
    System.out.println("Numbers Identified between 4 to 7");
    
    String decimal = "-10.123";
    if(decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
    System.out.println("Numbers Identified between 4 to 7");
    
    String decimal = "123..4";
    if(!decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
    System.out.println("Decimal not in range or different format");
    
    String decimal = "132";
    if(!decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
    System.out.println("Decimal not in range or different format");
    
    String decimal = "1.1";
    if(!decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
    System.out.println("Decimal not in range or different format");
    

    Hope it will help manyone.

提交回复
热议问题