Bruce Chung Bruce Chung - 1 year ago 101
Java Question

How can I convert certain characters of a String into a Float in Java?

I've been webscrapping some some data from a web page, in this case I just need a exchange rate.

By webscaprapping I got a String with this info


But I just need a float number with this


My code looks like this (the variable datos can be used to save the float number)

public static void main(String [] args) throws IOException{
float datos = 0;
String tasa = null;
Document d = Jsoup.connect("").timeout(6000).get();
Elements ele="span#lblRefSellMsg");
tasa = (ele.text());


Answer Source

Kind of a duplicate of the question: java : convert float to String and String to float

But to answer your question: If the web element always has a currency token/symbol prefixed before the float number you want, you could simply parse the string by using something like:

tasa = ele.text().subString(1, ele.text().length());
datos = Float.parseFloat(tasa);

this would parse out the leading 1st character - the currency identifier - then attempt to take the float value from string and read into float variable data type.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download