iPhone:如何在没有舍入的情况下截断浮点数?

时间:2011-10-07 17:51:54

标签: iphone floating-point truncate

我需要简单地截断浮点数(截断而不是舍入)。

float FloatNum = 43.6823921;
NSString *numString = [NSString stringWithFormat:@"%.1f", FloatNum]; // yields 43.7

2 个答案:

答案 0 :(得分:2)

您可以采用多种方法,但您的解决方案将取决于多种因素。

这将永远截断到十分之一。

float floatNum = 43.6823921;
float truncatedFloat = truncf(floatNum * 10) / 10;

如上所述,您可以将其转换为字符串并获取子字符串。如果你不总是处理两位数字,你可能想用rangeOfString: os来找到小数。

另一种选择是使用NSDecimalNumber方法decimalNumberByRoundingAccordingToBehavior:来明确设置舍入。我已经多次使用这个选项来处理准确性非常重要的货币操纵。

float num = 43.6894589;
NSDecimalNumber *decimalNumber = [NSDecimalNumber decimalNumberWithDecimal:[[NSNumber numberWithFloat:num] decimalValue]];
float truncatedFloat = [[decimalNumber decimalNumberByRoundingAccordingToBehavior:self] floatValue];

// NSDecimalNumberBehaviors
- (NSDecimalNumber *)exceptionDuringOperation:(SEL)method error:(NSCalculationError)error leftOperand:(NSDecimalNumber *)leftOperand rightOperand:(NSDecimalNumber *)rightOperand {
    return [NSDecimalNumber notANumber];
}

- (short)scale {
    return 1;
}

- (NSRoundingMode)roundingMode {
    return NSRoundDown;
}

答案 1 :(得分:1)

这会将float转换为string,将子串转换为索引4,转换回float。我认为这是截断浮点数而不进行舍入的常用方法:float myTruncatedFloat = [[[[NSNumber numberWithFloat:43.6823921] stringValue] substringToIndex:4] floatValue];。这会将43.6823921转换为43.68

float myfl = 43.6823921;
NSNumber *num = [NSNumber numberWithFloat:myfl];
NSString *numStr = [num stringValue];
NSLog(@"%@", numStr);
NSLog(@"%@", [numStr substringToIndex:2]);
NSLog(@"%@", [numStr substringToIndex:3]);
NSLog(@"%@", [numStr substringToIndex:4]);
NSLog(@"%@", [numStr substringToIndex:5]);    
NSLog(@"%@", [numStr substringToIndex:6]);
NSLog(@"%@", [numStr substringToIndex:7]);
NSLog(@"%@", [numStr substringToIndex:8]);
float newMyFloat = [[numStr substringToIndex:4] floatValue];
NSLog(@"%.1f", newMyFloat);
newMyFloat = [[numStr substringToIndex:5] floatValue];
NSLog(@"%.2f", newMyFloat);

打印:

[AppDelegate application:didFinishLaunchingWithOptions:]: 43.68239
[AppDelegate application:didFinishLaunchingWithOptions:]: 43
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.6
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.68
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.682
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.6823
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.68239
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.6
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.68