Tag: 舍入

为什么NSString类在格式化数字时不一致?

下面两行的输出似乎表明,NSString的stringWithFormat语句不会一致地舍入数字。 似乎从0.75到0.8正确地凑齐了。 但是它下降了0.25到0.2。 这是代码。 NSString *sRoundedScore = [NSString stringWithFormat:@"%.1f", fScore]; NSLog(@"\r\n score before rounding: %f, rounded score: %@", fScore, sRoundedScore); 当fScore分配为0.25时,输出为: score before rounding: 0.250000, rounded score: 0.2 当fScore分配为0.75时,输出为: score before rounding: 0.750000, rounded score: 0.8 我不得不开始使用NSNumberFormatter来使这个循环一直向上。 为什么stringWithFormat会在结果中产生这种变化?