1

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;
}
Igor Bizi
  • 105
  • 10

2 Answers2

0

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

Viral Savaj
  • 3,379
  • 1
  • 26
  • 39
0

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.

Andrea
  • 26,120
  • 10
  • 85
  • 131