开发者

Rounding large integers - objective-c

开发者 https://www.devze.com 2023-02-05 12:34 出处:网络
How might I achieve the following in objective-c? Start with an integer x between 0 and 999,999,999. And end up with an integer y.

How might I achieve the following in objective-c?

Start with an integer x between 0 and 999,999,999. And end up with an integer y.

If x is between 0 and 9999, then y = x Otherwise, x becomes something like 45k (representing 45,000) or 998m (representing 998 million). In other words, use the characters "k" and "m" in order to keep y under or equal to 4 c开发者_StackOverflow中文版haracters long.


Doesn't round but simply cuts off:

NSString *text;
if (x >= 1000000) text = [NSString stringWithFormat:@"%dm",x/1000000];
else if (x >= 1000) text = [NSString stringWithFormat:@"%dk",x/1000];
else text = [NSString stringWithFormat:@"%d",x];

Rounding solution:

NSString *text;
if (x >= 1000000) text = [NSString stringWithFormat:@"%.0fm",x/1000000.0f];
else if (x >= 1000) text = [NSString stringWithFormat:@"%.0fk",x/1000.0f];
else text = [NSString stringWithFormat:@"%d",x];

If you want greater precision, use float and %.1f etc.


thousands = x / 1000;
millions = thousands / 1000;
billions = millions / 1000;

if( billions )
  sprintf(y, "%dB", billions);
else if( millions)
  sprintf(y, "%dM", millions);
else if( thousands )
  sprintf(y, "%dK", thousands);
else 
  sprntf(y, "%d", x);


NSString *y = nil;

// If Billion
if (x >= 1000000000) y = [NSString stringWithFormat:@"%.0fB", x/1000000000];
// If Million
else if (x >= 1000000) y = [NSString stringWithFormat:@"%.0fM", x/1000000];
// If it has more than 4 digits
else if (x >= 10000) y = [NSString stringWithFormat:@"%.0fK", x/1000];
// If 4 digits or less
else y = [NSString stringWithFormat:@"%d", x];

Update: Added the missing 'else', otherwise it wouldn't get numbers with less than 4 digits.

0

精彩评论

暂无评论...
验证码 换一张
取 消