3 回答
TA贡献1803条经验 获得超3个赞
感谢大家的指导,我设法提出了一个解决方案:
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];
上面的代码适用于我抛出的测试用例,但是如果有人知道一种更好的方法,我很想听听它!
TA贡献1815条经验 获得超10个赞
float floatVal = 1.23456;
四舍五入
int roundedVal = lroundf(floatVal);
NSLog(@"%d",roundedVal);
围捕
int roundedUpVal = ceil(floatVal);
NSLog(@"%d",roundedUpVal);
四舍五入
int roundedDownVal = floor(floatVal);
NSLog(@"%d",roundedDownVal);
TA贡献1824条经验 获得超8个赞
一种简单的方法:
float theFloat = 1.23456;
int rounded = roundf(theFloat); NSLog(@"%d",rounded);
int roundedUp = ceil(theFloat); NSLog(@"%d",roundedUp);
int roundedDown = floor(theFloat); NSLog(@"%d",roundedDown);
// Note: int can be replaced by float
- 3 回答
- 0 关注
- 516 浏览
添加回答
举报