patternjavaMinor
Limit an integer to certain number of digits and suffix '+'
Viewed 0 times
suffixnumberlimitdigitsandcertaininteger
Problem
I am having a problem describing what the following code does. Below is my attempt at its javadoc.
The idea is simple enough. For any value greater than
/**
* Convert an integer so that the notion of its size fits within a certain number digits.
* e.g.
* Fit 123 to 2 digits -> 99+
* @param in The integer
* @param order The order of magnitude to fit it in.
* @return The 'countified' String.
*/
public static String countify(int in, int order) {
final int max = (int) Math.pow(10, order);
if (in >= max) {
return String.valueOf(max - 1) + "+";
} else {
return String.valueOf(in);
}
}The idea is simple enough. For any value greater than
10^order it returns 10^order - 1 plus a + (e.g. 123, with order 2 becomes 99+), else it returns the number itself. How do I better describe it? Thanks!Solution
Use less powerful language constructs
You use
Using
Here the ternary operator comes to the rescue. It looks hard but really is very easy to use.
If
You can now write
You use
if and elseif (in >= max) {
return String.valueOf(max - 1) + "+";
} else {
return String.valueOf(in);
}Using
if and else duplicates return String.valueOfHere the ternary operator comes to the rescue. It looks hard but really is very easy to use.
condition ? a : bIf
condition is true, than a, else b. As easy as that.You can now write
return String.valueOf just one time:return String.valueOf(in >= max ? (max - 1) + "+" : in)Code Snippets
if (in >= max) {
return String.valueOf(max - 1) + "+";
} else {
return String.valueOf(in);
}condition ? a : breturn String.valueOf(in >= max ? (max - 1) + "+" : in)Context
StackExchange Code Review Q#105370, answer score: 7
Revisions (0)
No revisions yet.