我的号码是1299。
我想显示为1.2K
我在下面试过,但它给出了1.3K
int mLike
NSString *mString = [NSString stringWithFormat:@"%d", mLike];
if (mLike>=1000) {
mString = [NSString stringWithFormat:@"%0.1fK", mLike*1.0/1000];
}
mString = [mString stringByReplacingOccurrencesOfString:@".0" withString:@""];
likeLabel.text = [NSString stringWithFormat:@"%@ LIKES", mString];
这给了我1.3 K
任何想法我怎么能把它作为1.2K?
答案 0 :(得分:3)
NSInteger mLike = 1301;
NSString *mString = [NSString stringWithFormat:@"%d", mLike];
if (mLike>=1000)
{
mLike = mLike - (mLike%100); // this was missing in your code. Subtract the remainder from the total inorder to get the desired result.
mString = [NSString stringWithFormat:@"%0.1fK", mLike*1.0/1000];
}
mString = [mString stringByReplacingOccurrencesOfString:@".0" withString:@""];
NSLog(@"%@",[NSString stringWithFormat:@"%@ LIKES", mString]);
答案 1 :(得分:1)
再审阅一下。
int mLike = 1299;
if(mLike >= 1000)
{
NSLog(@"%@K",[NSString stringWithFormat:@"%1.1f",floorf(mLike/100)/10]);
//OR
NSLog(@"%@K",[NSString stringWithFormat:@"%1.2f",floorf(mLike/10)/100]);
NSLog(@"%@K",[NSString stringWithFormat:@"%1.3f",floorf(mLike/1)/1000]);
}
结果:
test[2427:303] 1.2K
test[2427:303] 1.29K
test[2427:303] 1.299K
已编辑正如@kirit Modi先评论一样。
答案 2 :(得分:0)
int mLike = 1299;
NSMutableString *mString = [NSMutableString stringWithFormat:@"%d", mLike];
if(mLike >= 1000)
{
[mString insertString:@"." atIndex:mString.length - 3];
[mString deleteCharactersInRange:NSMakeRange(mString.length - 2, 2)];
[mString appendString:@"K"];
}
likeLabel.text = [NSString stringWithFormat:@"%@ LIKES", mString];