精确舍入浮点值,并在Objective-C中输出所需的小数点

时间:2013-04-25 14:06:37

标签: objective-c floating-point numbers

如何准确地对float value 1.449567进行精确处理。

输出值应为必需的小数点浮点值

输出应该是这样的:

for 1 decimal point  **f=1.5**
for 2 decimal point  **f=1.45**
for 3 decimal point  **f=1.450**
for 4 decimal point  **f=1.4496**

1 个答案:

答案 0 :(得分:1)

我建议使用NSNumberFormatter

示例:

float roundedValue =1.45999f;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:1];
[formatter setRoundingMode: NSNumberFormatterRoundDown];

NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:roundedValue]];