Asiimwe
Asiimwe

Reputation: 2259

How to Extract float numeric data from a string

Hey Guys i am using Google Currency Api to request for currency conversions information. For example i use Google Currency Api

to convert 1USD to my local Currency. The string returned is {lhs: "1 U.S. dollar",rhs: "2 481.38958 Ugandan shillings",error: "",icc: true} I need java code to extract the 2481.38958 float data type and save it in a float Variable. Please Help. Thanks alot.

Upvotes: 0

Views: 4343

Answers (4)

JuanZe
JuanZe

Reputation: 8167

If the response always contains the same pattern (with Ugandan shillings text), one possible way of doing it is something like this:

package so;

import java.util.StringTokenizer;

public class DemoString {

    public static void main(String[] args) {
        String s = new String("{lhs: \"1 U.S. dollar\",rhs: \"2 481.38958 Ugandan shillings\",error: \"\",icc: true}") ;
        StringTokenizer st = new StringTokenizer(s, "\"");
        st.nextToken();  //{lhs: 
        st.nextToken();  //1 U.S. dollar
        st.nextToken();  //,rhs: 
        String value = st.nextToken();  //2 481.38958 Ugandan shillings
        String num = value.substring(0, value.indexOf("U"));  // 2 481.38958 
        num = num.replaceAll(" ", "");
        Float fnum = 0f;
        try {
            fnum = Float.parseFloat(num);           
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
        System.out.println("The float number is: " + fnum.toString());
    }

}

Upvotes: 0

Reimeus
Reimeus

Reputation: 159844

For your input JSON string:

{lhs: "1 U.S. dollar",rhs: "2481.38958 Ugandan shillings",error: "",icc: true}

Using http://json-lib.sourceforge.net/ :

    JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );        
    String dollarString = json.getFloat( "rhs" );
    float dollars = Float.parseFloat(dollarString.split(" ")[0]);

Upvotes: 3

elias
elias

Reputation: 15490

Considering the value always will be between rhs: and a word.

String str = "{lhs: \"1 U.S. dollar\",rhs: \"2 481.38958 Ugandan shillings\",error: \"\",icc: true}";
Matcher m = Pattern.compile("rhs:\\s.*?([\\d\\s\\.]+)\\s\\w+").matcher(str);
m.find();
float value = Float.parseFloat(m.group(1).replaceAll("[^\\d\\.]", ""));
System.out.println(value);

Upvotes: 0

Thierry
Thierry

Reputation: 5243

This string is at JSON format. There are libs for manipulate this as an object. Examples : GSON (http://code.google.com/p/google-gson/) or http://www.json.org/java/

Something like : new JSONObject("{lhs: "1 U.S. dollar",rhs: "2 481.38958 Ugandan shillings",error: "",icc: true}").get("rhs")

And after you have to suppress unit, maybe with a regexp. And finally... Float.parseFloat("2 481.38958")

Upvotes: 0

Related Questions