I have weight values, they can be like 75kg and 75.5kg.
I want to have this values two styles: 75kg, 75.5kg, but NOT 75.0kg. How can I do it?
I have this solution, but I not like it
//show difference in 75 and 75.5 values style
NSString *floatWeight = [NSString stringWithFormat:@"%.1f",weightAtThePoint.floatValue];
NSString *intWeight = [NSString stringWithFormat:@"%.0f.0",weightAtThePoint.floatValue];
NSString *resultWeight;
if ([floatWeight isEqualToString:intWeight]) {
resultWeight = [NSString stringWithFormat:@"%.0f",weightAtThePoint.floatValue];
} else {
resultWeight = floatWeight;
}
If you don't like your solution, then take look at my solution
float flotvalue = weightAtThePoint.floatValue;
int reminder = flotvalue / 1.0;
if (reminder==flotvalue) {
NSLog(@"%f",flotvalue); //75KG Solution
}
else {
//75.xx solution
}
Enjoy Coding
The best solution would be using a number formatter:
static NSNumberFormatter * numberformatter = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
numberformatter = [[NSNumberFormatter alloc] init];
[numberformatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberformatter setMaximumFractionDigits:1];
[numberformatter setMinimumFractionDigits:0];
[numberformatter setLocale:[NSLocale currentLocale]];
});
Since the number formatter creation requires some resources is better if you create a single instance.
When you need to print a string just call this:
NSString * formattedString = [numberformatter stringFromNumber: weightAtThePoint];<br>
NSNumberFomatter
prints only the decimal number if it is different from 0 and it also helps you in choosing the correct decimal separator by using the current locale on the device.
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.