0

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!

4

3 に答える 3

2

単純なNSNumberFormatterでこれを実現できます。

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

もちろん、これは、保持したい10分の1の小数しかないことを前提としています。たとえば、「1.52」を使用した場合、これは「1.5」を返しますが、数値を「.5」に丸めた最後の投稿から判断すると、これはすべきではありません。問題になります。

于 2012-09-07T07:58:20.527 に答える
2

modf小数部分がゼロに等しいかどうかを確認するために使用できます。

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

    return fractional == 0.00 ? YES : NO;
}

一部の境界ケースでも機能します。

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

出力

a NO
b YES
c NO

数値が整数に非常に近い場合、他のソリューションは機能しません。この要件があるかどうかはわかりません。

その後、 を使用して好きなように表示できますNSNumberFormatter。1 つは整数用、もう 1 つは分数用です。

于 2012-09-07T08:13:17.947 に答える
1

このコードはあなたが望むものを達成します

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

こういうことはカテゴリーでできるのでどうでしょうか。

// 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]);
于 2012-09-07T08:00:48.403 に答える