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
通过webscaprapping,我得到了一个包含此信息的字符串
¢559.41
But I just need a float number with this
但我只需要一个浮点数
559.41
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("http://indi-eco.appspot.com/tcd").timeout(6000).get();
Elements ele= d.select("span#lblRefSellMsg");
tasa = (ele.text());
}}
2 个解决方案
#1
1
Kind of a duplicate of the question: java : convert float to String and String to float
类似于问题的副本:java:将float转换为String,将String转换为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:
但是要回答你的问题:如果web元素总是在你想要的浮点数之前有一个前缀的货币标记/符号,你可以简单地通过使用类似的东西来解析字符串:
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.
这将解析前面的第一个字符 - 货币标识符 - 然后尝试从字符串中获取浮点值并读取浮点变量数据类型。
#2
0
If the String contains text
then numeric then you can use this regex to match or split
如果字符串包含文本然后是数字,那么您可以使用此正则表达式进行匹配或拆分
(([1-9]\d{0,2}(,\d{3})*)|(([1-9]\d*)?\d))(\.\d\d)?$
see https://regex101.com/r/PLioEH/1 and https://*.com/a/17867041/2310289
请参阅https://regex101.com/r/PLioEH/1和https://*.com/a/17867041/2310289
and then pass the resulting string to Float.valueof (str);
然后将结果字符串传递给Float.valueof(str);
#1
1
Kind of a duplicate of the question: java : convert float to String and String to float
类似于问题的副本:java:将float转换为String,将String转换为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:
但是要回答你的问题:如果web元素总是在你想要的浮点数之前有一个前缀的货币标记/符号,你可以简单地通过使用类似的东西来解析字符串:
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.
这将解析前面的第一个字符 - 货币标识符 - 然后尝试从字符串中获取浮点值并读取浮点变量数据类型。
#2
0
If the String contains text
then numeric then you can use this regex to match or split
如果字符串包含文本然后是数字,那么您可以使用此正则表达式进行匹配或拆分
(([1-9]\d{0,2}(,\d{3})*)|(([1-9]\d*)?\d))(\.\d\d)?$
see https://regex101.com/r/PLioEH/1 and https://*.com/a/17867041/2310289
请参阅https://regex101.com/r/PLioEH/1和https://*.com/a/17867041/2310289
and then pass the resulting string to Float.valueof (str);
然后将结果字符串传递给Float.valueof(str);