0
我有一个字符串"+1.29%"
或如何比较字符串的百分比?
我怎么能转换成一个float或double这样我就可以比较值呢?
这是我比较类看起来像:
package org.stocktwits.helper;
import java.util.Comparator;
import org.stocktwits.model.Quote;
public class PercentChangeComparator implements Comparator<Quote>
{
public int compare(Quote o1, Quote o2) {
try{
String subChange1 = o1.getPercentChange();
String subChange2 = o2.getPercentChange();
float change1 = Float.valueOf(subChange1.substring(0, subChange1.length() - 1));
float change2 = Float.valueOf(subChange2.substring(0, subChange2.length() - 1));
if (change1 < change2) return -1;
if (change1 == change2) return 0; // Fails on NaN however, not sure what you want
if (change2 > change2) return 1;
return 0;
}catch(NullPointerException e){ System.out.println(e); return 0;}
catch(NumberFormatException e){ System.out.println(e); return 0;}
}
}
我认为 - 但我想我失去了一些东西笑不答。 – 2010-09-14 01:42:22
而不是检查change1并更改为并返回1,0或-1。 “返回change2 - change1;”可能更容易 – Dunderklumpen 2010-09-14 05:33:36
String subChange1 = o1.getPercentChange(); \t \t String foo = subChange1.substring(0,subChange1.length() - 1); //给我一个空指针异常... – 2010-09-14 06:20:53