如何比较字符串的百分比?

时间:2010-09-14 01:32:51

标签: java string casting comparator

我有一个字符串"+1.29%""-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;}
        }
    }

2 个答案:

答案 0 :(得分:4)

如何剥离百分号然后转换为数字?

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

答案 1 :(得分:1)

只需观察您的异常处理。返回0表示值相等,当字符串无效时,您可能不需要这些值。

无论如何,尝试这样的事情:

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