2011-10-07 77 views

回答

1

這會將float轉換爲字符串,將substring轉換爲索引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 
+0

這是一種方法。有沒有一種方法可以在不四捨五入的情況下實際截斷浮點數? – Marsman

+0

這會將float轉換爲字符串,將子字符串轉換爲索引4,將其轉換回float。我認爲這是通常的截斷一個浮點而不捨入四捨五入的方法:'float myTruncatedFloat = [[[[NSNumber numberWithFloat:43.6823921] stringValue] substringToIndex:4] floatValue];'。這會將'43.6823921'轉換爲'43.68'。 – chown

2

有很多方法可以做,但您的解決方案將取決於多種因素。

這將永遠截斷到十分之一的地方。

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

正如CHOWN提到的,可以將其轉換爲字符串,並採取子。如果您不總是處理雙位數字,您可能需要使用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; 
}