Android如何获得号码结束

时间:2015-05-27 09:35:05

标签: android

在我的项目中,我得到一个项目列表,我必须在列表项上写下他的编号,并带有“数字结尾”,例如:

第1,第2,第3等等,列表很长。

是否有正确的方法来设置数字结束?

谢谢!

1 个答案:

答案 0 :(得分:3)

public String NumberWithSuffix(int number) {
        if (String.valueOf(number).endsWith("11")) return String.valueOf(number) + "th";
        if (String.valueOf(number).endsWith("12")) return String.valueOf(number) + "th";
        if (String.valueOf(number).endsWith("13")) return String.valueOf(number) + "th";
        if (String.valueOf(number).endsWith("1")) return String.valueOf(number) + "st";
        if (String.valueOf(number).endsWith("2")) return String.valueOf(number) + "nd";
        if (String.valueOf(number).endsWith("3")) return String.valueOf(number) + "rd";
        return String.valueOf(number) + "th";
    }

优化代码。

 public String NumberWithSuffix(int number) {

        String outputNumber = "";
        String numberString = String.valueOf(number);

        if (String.valueOf(number).endsWith("11")) {
            outputNumber = numberString + "th";
        } else if (String.valueOf(number).endsWith("12")) {
            outputNumber = numberString + "th";
        } else if (String.valueOf(number).endsWith("13")) {
            outputNumber = numberString + "th";
        } else if (String.valueOf(number).endsWith("1")) {
            outputNumber = numberString + "st";
        } else if (String.valueOf(number).endsWith("2")) {
            outputNumber = numberString + "nd";
        } else if(String.valueOf(number).endsWith("3")) {
            outputNumber = numberString + "rd";
        } else {
            outputNumber = numberString + "th";
        }
        return outputNumber;
    }