views:

82

answers:

2

I have a string "+1.29%" or "-1.29%"

How can I convert this into a float or double so I can compare the values?

This is how my comparator class looks like:

 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;}
        }
    }
+4  A: 

What about stripping off the percent symbol and then converting to number?

s.substring(0, s.length - 1)
Nikita Rybak
I thought that - but didn't answer as I thought I was missing something lol.
Preet Sangha
Rather than checking change1 and change to and returning 1, 0 or -1. It might be easier to just "return change2 - change1;"
Dunderklumpen
String subChange1 = o1.getPercentChange(); String foo = subChange1.substring(0, subChange1.length() - 1); //gives me a nullpointer exception...
Sheehan Alam
+1  A: 

Just watch your exception handling. Returning 0 means the values equal, which you might not want when the Strings are not valid.

Anyway, try something like this:

DecimalFormat df = new DecimalFormat("+####.##%;-####.##%");
Double double1 = (Double)df.parse("+12.34%");
Double double2 = (Double)df.parse("-12.34%");

//including test
assertThat(double1, equalTo(Double.valueOf(.1234)));
assertThat(double2, equalTo(Double.valueOf(-.1234)));

assertThat(double1.compareTo(double2), equalTo(1));
assertThat(double1.compareTo(double1), equalTo(0));
assertThat(double2.compareTo(double1), equalTo(-1));
Steven