PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 20, 2022

[FIXED] How to check a string is float or int?

 July 20, 2022     int, java, string     No comments   

Issue

I have a string and I know that is only contained a number.

I want to check this number is int or float.


Solution

There are many ways to solve your problem for example you can use try{}catch(){}:

Solution 1

public static void main(String[] args) {
    String str = "5588";
    //check if int
    try{
        Integer.parseInt(str);
    }catch(NumberFormatException e){
        //not int
    }
    //check if float
    try{
        Float.parseFloat(str);
    }catch(NumberFormatException e){
        //not float
    }
}

Solution 2

Or you can use regex [-+]?[0-9]*\.?[0-9]+ :

boolean correct = str.matches("[-+]?[0-9]*\\.?[0-9]+");

For more details take a look at this Matching Floating Point Numbers with a Regular Expression



Answered By - Youcef Laidani
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing