开发者

How to compare percentages that are strings?

开发者 https://www.devze.com 2023-01-16 04:56 出处:网络
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?

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) {
        开发者_如何学JAVA    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;}
        }
    }


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

s.substring(0, s.length - 1)


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));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号