我已经对'legInches'进行了舍入,但是如何将其舍入到2个小数点而不是没有?
具体 - (int)round(legInches)
result = (isTitle)? @"Leg Span" : [NSString stringWithFormat:@"%dcm / %din", (int)legCentimetres, (int)round(legInches)];
答案 0 :(得分: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];