我需要簡單地截斷浮點數(截斷而不是圓)。iPhone:如何截斷未經四捨五入的浮動?
float FloatNum = 43.6823921;
NSString *numString = [NSString stringWithFormat:@"%.1f", FloatNum]; // yields 43.7
我需要簡單地截斷浮點數(截斷而不是圓)。iPhone:如何截斷未經四捨五入的浮動?
float FloatNum = 43.6823921;
NSString *numString = [NSString stringWithFormat:@"%.1f", FloatNum]; // yields 43.7
這會將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
有很多方法可以做,但您的解決方案將取決於多種因素。
這將永遠截斷到十分之一的地方。
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;
}
你想要43嗎? – crashmstr
他希望43.6(不捨入,只是截斷) –