Question

I have an app that imports a long list of data of a csv.

I need to work with the numbers fetched, but in order to do this, I need to get rid of the decimal place on numbers that are ints, and leave untoched numbers that have x.5 as decimal

for example

1.0 make it 1
1.50 make it 1.5

what would be the best way to accomplish this?

thanks a lot!

Was it helpful?

Solution

You can use modf to check if the fraction part equates to zero or not.

-(BOOL)isWholeNumber:(double)number
{
    double integral;
    double fractional = modf(number, &integral);

    return fractional == 0.00 ? YES : NO;
}

Will work for some boundary cases as well.

float a = 15.001;
float b = 16.0;
float c = -17.999999;

NSLog(@"a %@", [self isWholeNumber:a] ? @"YES" : @"NO");
NSLog(@"b %@", [self isWholeNumber:b] ? @"YES" : @"NO");
NSLog(@"c %@", [self isWholeNumber:c] ? @"YES" : @"NO");

Output

a NO
b YES
c NO

Other solutions do not work if the number is very close to a whole number. I am not sure if you have this requirement.

After that you can display them as you like using the NSNumberFormatter, one for whole numbers and one for fractions.

OTHER TIPS

A simple NSNumberFormatter should achieve this for you:

float someFloat = 1.5;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setAllowsFloats:YES];
[formatter setMaximumFractionDigits:1];
NSString *string = [formatter stringFromNumber:[NSNumber numberWithFloat:someFloat]];

Of course this assumes that you only have decimals in the tenths that you want to keep, for example if you used "1.52" this would return "1.5" but judging by your last post on rounding numbers to ".5" this shouldn't be a problem.

This code achieves what you want

float value1 = 1.0f;
float value2 = 1.5f;
NSString* formattedValue1 = (int)value1 == (float)value1 ? [NSString stringWithFormat:@"%d", (int)value1] : [NSString stringWithFormat:@"%1.1f", value1];
NSString* formattedValue2 = (int)value2 == (float)value2 ? [NSString stringWithFormat:@"%d", (int)value2] : [NSString stringWithFormat:@"%1.1f", value2];

This kind of thing could be done in a category so how about

// untested
@imterface NSString (myFormats)
+(NSString)formattedFloatForValue:(float)floatValue;
@end

@implementation NSString (myFormats)
+(NSString)formattedFloatForValue:(float)floatValue
{
    return (int)floatValue == (float)floatValue ? [NSString stringWithFormat:@"%d", (int)floatValue] : [NSString stringWithFormat:@"%1.1f", floatValue];
}
@end

// usage
NSLog(@"%@", [NSString formattedFloatForValue:1.0f]);
NSLog(@"%@", [NSString formattedFloatForValue:1.5f]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top