Math.round(msgBody.length() / 160 + 0.5) Not Evaluating Correctly?
So I'm trying to dynamically calculate the number of SMS messages that will be sent for a given message length. SMS messages are chunked into 160 byte (character) chunks. I use MOD 160 <= 1 because I need to account for adding and subtracting text. For performance reasons I only want to do the numMsgs calculations near the boundaries: 0, 1, 160, 161, 320, 321, ...
The problem is at a msgBody length of 160 the rounding operation evaluates to 2 (160/160 = 1 + 0.5 rounded up). At multiples of 160 + 1 it should evaluate to the next highest integer because any 160 bytes + 1 byte equals a whole additional message.
I have made this work by using an OR operator and == 1 OR == 159. It increments and decrements correctly, but it only decrements at multiples of 160 -1 which is not correct.
Also, I can put IF logic inside the outer logic to simply subtract 1 if the MOD evaluates to 0 (zero), but that seemed kludgey and I'd rather learn the pa开发者_JS百科ttern I may be missing from my quiver :)
if (msgBody.length() % 160 <= 1) {
numMsgs.setText(Math.round(msgBody.length() / 160 + 0.5));
}
msgBody.length() / 160
is a division expressions with both sides being integers - so it will perform integer division. I suspect that's what you're doing wrong, but it's not entirely clear to be honest. (You claim it's not evaluating correctly, but you haven't given a sample input / output / expected output for us to look at.)
To be honest, the simplest approach is to round up like this:
numMsgs.setText((msgBody.length() + 159) / 160);
That's still performing integer division, but the +159 means it will round up if the input isn't exactly a multiple of 160.
I suggest you could perform that calculation regardless of the boundaries - but make sure you don't actually update the UI if there's no change compared with the existing value. It's going to be very cheap - one integer add and one integer divide.
If there is a message, then at least 1 SMS will be sent. You want
(length / 160) + (length%160 > 0 ? 1 : 0)
Just adding and dividing using int
is enough with the right formula. Modulo is probably even slower than dividing. However, it's not clear to me what result you expect... (msgBody.length() + 159) / 160
isn't enough?
精彩评论