Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting Float values from a string in Java

I have a string like this "Humidity: 14.00% Temperature:28.00 C".

I want to extract the two float values from the string, how can I do so?

like image 821
prashant Avatar asked Jun 03 '16 07:06

prashant


3 Answers

First, take a look at @Bathsheba`s comment.
I have a straightforward way, but that is not clever or universal.

String[] array = string.replaceAll("[Humidity:|Temperature:|C]", "").split("%");

You will receive String[]{"14.00", "28.00"} and then you may convert these values of the array into Float by using Float.parse() or Float.valueOf() methods.

Arrays.stream(array).map(Float::valueOf).toArray(Float[]::new);
like image 175
Andrew Tobilko Avatar answered Sep 27 '22 20:09

Andrew Tobilko


You can try this, using regex

String regex="([0-9]+[.][0-9]+)";
String input= "Humidity: 14.00% Temperature:28.00 C";

Pattern pattern=Pattern.compile(regex);
Matcher matcher=pattern.matcher(input);

while(matcher.find())
{
    System.out.println(matcher.group());
}
like image 33
Saurabh Avatar answered Sep 27 '22 21:09

Saurabh


(Disclaimer : You should look at @Andrew Tobilko' s answer if you want some much cleaner and reusable code).

First you need to separate your string into two substrings. You can do this using String a = yourString.substring(10,14); String b =yourString.substring(29,33);

Then, you use Float.parseFloat(String s) to extract a float from your strings :

Float c=Float.parseFloat(a); Float d= Float.parseFloat(b);

That is if your String is exactly the one that you wrote. Otherwise, you should make sure that you use the right indexes when you call String.substring(int beginIndex, int endIndex).

like image 37
Theo Sardin Avatar answered Sep 27 '22 20:09

Theo Sardin