我如何在objective-c中实现以下目标?
从0到999,999,999之间的整数x开始。 并以y整数结束。
如果x介于0和9999之间,则y = x 否则,x变为45k(代表45,000)或998m(代表9.98亿)。换句话说,使用字符“k”和“m”以使y保持低于或等于4个字符。
答案 0 :(得分:2)
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);
答案 1 :(得分:2)
不圆,但只是切断:
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];
舍入解决方案:
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];
如果您想要更高的精确度,请使用float
和%.1f
等
答案 2 :(得分:0)
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];
更新:添加了缺少的“其他”,否则不会获得少于4位的数字。