我的印象是,使用像%0.1f这样的格式说明符会在标准4/5分割后对浮点值进行舍入(即3.24将舍入为3.2,而3.25将舍入为3.3)。然而,我没有得到我期望的结果。这是我的测试代码:
NSLog(@"%0.1f", 3.24); //Output: 3.2
NSLog(@"%0.1f", 3.25); //Output: 3.2 Expected Output: 3.3
NSLog(@"%0.1f", 3.26); //Output: 3.3
即使使用NSNumberFormatter也会产生相同的结果:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setRoundingMode: NSNumberFormatterRoundHalfUp]; //Tried with and without setting this. Same results either way.
[formatter setMaximumFractionDigits:1];
NSString *numberString1 = [formatter stringFromNumber:[NSNumber numberWithFloat:3.24]];
NSString *numberString2 = [formatter stringFromNumber:[NSNumber numberWithFloat:3.25]];
NSString *numberString3 = [formatter stringFromNumber:[NSNumber numberWithFloat:3.26]];
NSLog(@"Result...%@",numberString1); //Output: 3.2
NSLog(@"Result...%@",numberString2); //Output: 3.2 Expected: 3.3
NSLog(@"Result...%@",numberString3); //Output: 3.3
似乎是基本的东西。我做错了什么?