Question

I have number as 1299.

I want to display as 1.2K

I tried below, but it gives as 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];

This gives me 1.3 K

Any idea how can I have it as 1.2K?

Was it helpful?

Solution

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

OTHER TIPS

Review This One Also.

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

Result :

test[2427:303] 1.2K
test[2427:303] 1.29K
test[2427:303] 1.299K

EDITED As Like @kirit Modi Also Commented First.

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];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top