0

I have rounded the 'legInches' but how do I round this to 2 decimal points instead of none?

specifically - (int)round(legInches)

result = (isTitle)? @"Leg Span" : [NSString stringWithFormat:@"%dcm / %din", (int)legCentimetres, (int)round(legInches)];
4

1 回答 1

1

简单的方法:

result = (isTitle)? @"Leg Span" : [NSString stringWithFormat:@"%dcm / %.2fin", (int)legCentimetres, legInches];

但是对于那些期望小数点分隔符以外的东西的人来说,这并不能正确地格式化数字。为此,您应该使用NSNumberFormatter.

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];
NSString *legInchesStr = [formatter stringFromNumber:@(legInches)];

result = (isTitle)? @"Leg Span" : [NSString stringWithFormat:@"%dcm / %@in", (int)legCentimetres, legInchesStr];
于 2013-06-06T22:42:20.250 回答