使用NSLog(@"%f", theFloat) 总是输出六位小数,例如:
float theFloat = 1;
NSLog(@"%f",theFloat);
输出:
1.000000
换句话说,你永远不会通过使用NSLog(@"%f", theFloat)获得1.123。
小数点后三位:
float theFloat = 1.23456;
float newFLoat = (int)(theFloat * 1000.0) / 1000.0;
NSLog(@"%f",newFLoat);
输出:
1.234000
四舍五入到小数点后三位(使用roundf() / lroundf() / ceil() / floor()):
float theFloat = 1.23456;
float newFLoat = (int)(roundf(theFloat * 1000.0)) / 1000.0;
NSLog(@"%f",newFLoat);
输出:
1.235000
四舍五入到小数点后三位(脏方法):
float theFloat = 1.23456;
NSString *theString = [NSString stringWithFormat:@"%.3f", theFloat];
float newFloat = [theString floatValue];
NSLog(@"%@",theString);
NSLog(@"%f",newFloat);
输出:
1.235
1.235000