I am trying to convert the value to float with 2 precision decimal format.
NSString* formattedNumber = [NSString stringWithFormat:@"%.2lu", (unsigned long)users.count];
float totalRatingCount = atof([formattedNumber UTF8String]);
This gives me values such as
1.000000
2.000000
3.000000
What I want is the following
1.00
2.00
3.00
Where am i going wrong?
A float has no precision value, it's not a fixed point value. However, there is an easier way to convert to float:
CGFloat totalRating = [formattedNumber floatValue];
to print a float with 2dp's of precision, use the format string @"%.02f"
You need to use %.2f
format specifier as
NSString* formattedNumber = [NSString stringWithFormat:@"%.2f", (float)users.count];
float totalRatingCount = atof([formattedNumber UTF8String]);
and you'll get the desired out put with 2 values precision after decimal.
Using NSNumberFormatter, you can rounding number up to two digit.
double d = 12.1278;
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setRoundingMode:NSNumberFormatterRoundFloor];
[formatter setMinimumFractionDigits:2];
[formatter setMaximumFractionDigits:2];
NSString *numberString = [formatter stringFromNumber:@(d)];
NSLog(@"numberString: %@", numberString);
Output is :
numberString: 12.12
Try this:
NSNumber *number = [NSNumber numberWithFloat:(unsigned long)users.count];
NSNumberFormatter* nf=[[NSNumberFormatter alloc]init];
nf.minimumFractionDigits=2;
nf.maximumFractionDigits=2;
NSString* str = [nf stringFromNumber:number];
NSLog(@"%@",str);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.