liliya woland wrote:Hi all, I'm testing something and want to create a scale for number length representation. Say I have a number 4333, I want to take the number and say it's in a category 1000. Or the number is 324, the scale should be in 100. I want to do this inline - no loop, no var declaration. I have right now what's below, but it's far from the desired result. I know how to do this in a loop, but I want to have it inline. Seems like an interesting puzzle. If anyone can think of something, please let me know. Here is what I have:
May I ask for the reason of avoiding a loop? Is it purely as a puzzle?
I'm doing this in Jasper iReport in a place where a variable is expected, not a scriptlet.
In that case, why don't you just put a method invocation there, and use a loop within the method body?
liliya woland wrote:I was hoping there is a cleaner way than a clunky loop.
Well, you do know that your current solution also have a loop right ? ... it is just hidden in the Integer toString() method. If you implement a loop, that is specific to the task, clunky or not, it should be (unless you mess it up) more efficient than the loop that is designed for something else (to convert an int to a string).
seems VERY clunky, to me.
liliya woland wrote:If anyone can think of something, please let me know.
Well, BigDecimal.valueOf(testNum).precision() will return the length of an integer in decimal digits. Still pretty clunky, but maybe a bit clearer. Clearer still if you put it in a utility method (numDigits(int) ?).
However, if all you're trying to do is fit it in a predetermined space, what about using String.format()?
fred rosenberger wrote:This:
seems VERY clunky, to me.
Also, it doesn't produce the desired results.
testNum = 4333 produces 40, should be 1000
testNum = 324 produces 30, should be 100
Liliya, I agree with others that the idea of avoiding a "clunky loop" is misguided. There are loops in most any library code you might call. You have a choice between writing the loop yourself, or calling code which does the loop for you. I like Winston's suggestion. Another approach is:
which is also clunky looking, but works.
Once again, looking at the source would reveal hidden loops. Oh well.
Mike Simmons wrote:Once again, looking at the source would reveal hidden loops.
Not with BigDecimal I don't think. For anything that fits in an int, I'm pretty certainly its just a multiplication and right-shift 31. But hey, what's a loop between friends?
Damn! I hadn’t seen that post. I tend to open multiple tabs (since the previous/next buttons no longer exist), and posts can slip in which I don’t notice. I can have delays of over twenty minutes like that.
Mike Simmons wrote:Um, nothing? Which is why I suggested it.
Sorry for missing that.