HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Limit an integer to certain number of digits and suffix '+'

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
suffixnumberlimitdigitsandcertaininteger

Problem

I am having a problem describing what the following code does. Below is my attempt at its javadoc.

/**
 * 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 if and else

if (in >= max) {
    return String.valueOf(max - 1) + "+";
} else  {
    return String.valueOf(in);
}


Using if and else duplicates return String.valueOf

Here the ternary operator comes to the rescue. It looks hard but really is very easy to use.

condition ? a : b


If 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 : b
return String.valueOf(in >= max ? (max - 1) + "+" : in)

Context

StackExchange Code Review Q#105370, answer score: 7

Revisions (0)

No revisions yet.