需要帮助舍入数字(浮点数)

时间:2011-06-09 01:25:55

标签: objective-c ios cocoa-touch floating-point rounding

在下面的代码中,我希望将满足if (isKgs)的数字四舍五入为一个小数点。

例如,现在它正在给我2.2643534543,但我只想要2.3

有什么想法吗?

NSNumber *weightInPounds = [self.pickerArray objectAtIndex:row];
NSNumber *weightInKilos = [[DDUnitConverter massUnitConverter] convertNumber: weightInPounds fromUnit: DDMassUnitUSPounds toUnit: DDMassUnitKilograms]; 
NSString *temp = [NSString stringWithFormat:@"%@ kgs", [weightInKilos stringValue]];
[self.firstComponentText setString:temp];

我相信,选择器中的数字类型为float

1 个答案:

答案 0 :(得分:2)

您可以使用NSNumber对象格式化NSNumberFormatter对象。一个例子,

NSNumber * decimal = [NSNumber numberWithFloat:2.2643534543];

NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setRoundingMode:NSNumberFormatterRoundHalfUp]; 
[formatter setMaximumFractionDigits:1];

NSLog(@"%@", [formatter stringFromNumber:decimal]);