2

I have the following function which gets an integer (from a database but I have checked that the number is sent properly in the function). I want to transform to string and return it in a specific way depending how large the number is.

For some weird reason it works fine with numbers < 10000, but from that point on it just shows weird results

Function is:

public static String numberTransformation(int number){
    String str=String.valueOf(number);
    System.out.println("#################### NUMBER BEFORE TRANSFORMATION" + str);
    if(number<=999){
        return str;
    }
    else if(number>999 && number<1099){
        return "1k";
    }
    else if(number>1099 && number<=9999){
        return str.charAt(0) + "." + str.charAt(1) + "k";
    }
    else if (number>9999 && number<=99999){
        return str.charAt(0) + str.charAt(1) + "k";
    }
    else if (number>99999 && number<=999999){
        return str.charAt(0) + str.charAt(1) + str.charAt(2) + "k";
    }
    return "";
}

Some tests and results:

Number is 999 -> result is 999 (expected)
Number is 2532 -> result is 2.5k (expected)
Number is 10000 -> result is 97k (not expected)
Number is 100000 -> result is 145k (not expected)

What did I do wrong? Does it have something to do with the number being larger than 10000?

Eran
  • 387,369
  • 54
  • 702
  • 768
Vaggouras
  • 59
  • 1
  • 7
  • This supposed duplicate is only useful if you already know the answer to the question. The OP assumed he/she were concatenating Strings, not adding chars, so they didn't know enough to search for a question about char addition. While it is helpful for this question to be linked to the other one, deleting this question (which is probably the goal of the closer of this question) won't help users that confuse String concatenation with char addition find the answer in the dupe target. – Eran Jan 24 '17 at 06:48

1 Answers1

9
return str.charAt(0) + str.charAt(1) + "k";

does not concatenate the first and second characters of str, it adds the numeric value of the two chars.

In your example, the numeric value of '1' (49) and the numeric value of '0' (48) are added, and you get 97 + "k" instead of "10k".

Instead, use:

return "" + str.charAt(0) + str.charAt(1) + "k";

or

return str.substring(0,2) + "k";

in order to perform String concatenation.

The same goes for:

return str.charAt(0) + str.charAt(1) + str.charAt(2) + "k";

which should be changed to:

return "" + str.charAt(0) + str.charAt(1) + str.charAt(2) + "k";

or:

return str.substring(0,3) + "k";

As an alternative, you can use a StringBuilder instead of String concatenation.

Eran
  • 387,369
  • 54
  • 702
  • 768