There are three things I see as being significant issues with your code, and also a suggestion about your method's name.
Orphaned Else
When you have an if-statement with a guaranteed return in it, there's no need for an else-block. Your code would be better as:
if (in >= max) {
return String.valueOf(max - 1) + "+";
}
return String.valueOf(in);
Input validation
- bad orders: your code will produce unexpected results for values with an order outside the range of 1..10. An order of -1 implies a "max" of 0.1, which will become 0, which will mean values like 10 will be presented as
-1+
.... which is hard to fathom.
- bad values: Negative input values will cause consternation. An order of 2 implies 2-digits of value, but the input
-12345
will output as -12345
. Your code does not have a good way of expressing negative input values, so I don't know what to recommend other than avoiding them entirely, and throwing an IllegalArgumentException for negative input.
Edge Cases
Orders larger than 10 will effectively truncate to Integer.MAX_VALUE
, which makes Integer.MAX_VALUE an interesting input..... An order of 10 and an input of Integer.MAX_VALUE, would normally imply an output of 2147483647
, but you respond with 2147483646+
Name
The term "clamp" is often used when confronted with this.... where a value is clamped to be within a range, or limit. I would use that as the function name.
Solution
I would recommend transfroming your internal logic to use long, and be done with it... ;-)
public static String clamp(int in, int order) {
if (order < 0 || in < 0) {
throw new IllegalArgumentException("Inputs are required to be positive");
}
long max = (long)Math.pow(10, order);
if (max > Integer.MAX_VALUE || in < max) {
return String.valueOf(in);
}
return String.valueOf(max - 1) + "+";
}