I can't achieve r开发者_JAVA技巧ounding a float.
Those calls all returns me 3.5999999 and not 3.6 for theoTimeoutTrick and theoTimeout.
How may I achieve to get that 3.6 value, into NSString AND float vars ?#define minTimeout 1.0
#define defaultNbRetry 5
float secondsWaitedForAnswer = 20.0;
float minDelayBetween2Retry = 0.5;
int theoNbRetries = defaultNbRetry;
float theoTimeout = 0.0;
while (theoTimeout < minTimeout && theoNbRetries > 0) {
theoTimeout = (secondsWaitedForAnswer - (theoNbRetries-1)*minDelayBetween2Retry) / theoNbRetries;
theoNbRetries--;
}
float theoTimeoutTrick = [[NSString stringWithFormat:@"%.1f", theoTimeout] floatValue];
theoTimeout = roundf(theoTimeout * 10)/10.0;
From Rounding numbers in Objective-C:
float roundedValue = round(2.0f * number) / 2.0f;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:1];
[formatter setRoundingMode: NSNumberFormatterRoundDown];
NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:roundedValue]];
[formatter release];
That will get you a rounded string. You can parse it back into a float I'm sure.
Okay, here's some test code and some results:
NSLog(@"%f", round(10*3.56)/10.0);
=>3.600000
NSLog(@"%f", round(10*3.54)/10.0);
=>3.500000
NSLog(@"%f", round(10*3.14)/10.0);
=>3.100000
Okay, you know what? Your original code works as intended on my machine, OSX 10.6 and Xcode 4. How exactly are you seeing your output?
精彩评论