J'ai une chaîne "+1.29%"
ou "-1.29%"
Comment comparer les pourcentages qui sont des chaînes?
Comment puis-je convertir en un flotteur ou double pour que je puisse comparer les valeurs?
Voici comment ma classe de comparaison ressemble à:
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;}
}
}
Je pensais que - mais n'a pas répondu que je pensais que je manque quelque chose lol. –
Plutôt que de vérifier change1 et de changer et retourner 1, 0 ou -1. Il pourrait être plus facile de simplement "retourner change2 - change1;" – Dunderklumpen
Chaîne subChange1 = o1.getPercentChange(); \t \t chaîne foo = subChange1.substring (0, subChange1.length() - 1); // me donne une exception nullpointer ... –