我无法实现四舍五入。
对于theoTimeoutTrick和theoTimeout,这些调用全部返回3.5999999而不是3.6。 我如何实现将3.6值转换为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;
答案 0 :(得分:3)
来自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];
那会给你一个圆形的字符串。你可以把它解析成一个我确定的浮动。
好的,这里有一些测试代码和一些结果:
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
好的,你知道吗?您的原始代码在我的机器,OSX 10.6和Xcode 4上按预期工作。您究竟如何看到输出?