繁体   English   中英

四舍五入大整数-Objective-C

[英]Rounding large integers - objective-c

如何在Objective-C中实现以下目标?

以0到999,999,999之间的整数x开头。 并以整数y结束。

如果x在0到9999之间,则y = x否则,x变成类似45k(代表45,000)或998m(代表9.98亿)。 换句话说,使用字符“ k”和“ m”以使y的长度保持在4个字符以下。

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 *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等。

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];

更新:添加了丢失的“ else”,否则它将不会获得少于4位数字的数字。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM