0

Hi everyone I am trying to get the numeric value inside a string. So far this method works well for me to obtain integers. But now I would also like to be able to obtain numbers that contain decimals.

if I want to extract the number that a String contains I use: getNumbers("delay: 5 days") output = 5

Now I want to get the number of "this a sample, delay: 7.1 days" output = 7.1 Remark: the str always can change, but always will have a number (integer or float)

public String getNumbers(String str){
        str = str.replaceAll("[^\\d]", " ");
        str = str.trim();
    
        str = str.replaceAll(" +", " ");
        
        if (str.equals(""))
           return "-1";
    
        return str;
    }
4
  • does Double#parseDouble(String) accomplish your needs? Commented Sep 6, 2021 at 22:15
  • 3
    Does this answer your question? Converting String to Number in Java Commented Sep 6, 2021 at 22:30
  • Your replaceAll, trim and replaceAll seems a little cumbersome... Commented Sep 6, 2021 at 22:31
  • This isn't a duplicate of the link given, since the primary programming problem in this question is isolating the characters that make up the number. But hey, anything will do for the close-at-all-costs crew. Commented Sep 6, 2021 at 22:52

2 Answers 2

1

You can use regex for retrieving only digits from string, try this:

String numbers = Double.valueOf(yourStrValue.replaceAll("[^\\d.]+|\\.(?!\\d)", "")).toString()

but watch out for discrete numbers will be merged by this way. For example if u have 34fdf^.98 this process produced 34.98

Sign up to request clarification or add additional context in comments.

1 Comment

Just use the R.E. to extract the number rather than replacing the characters that are not the number Matcher m = Pattern.compile("\\d+(\\.\\d+)?").match(str); if (m.find()) return Double.valueOf(m.group(0));
0

Try using Double.parseDouble(str) in order to parse the double value. However, keep in mind that you will need to remove all the non-number characters from the string.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.