NSNumber浮动值

rak*_*hNS 3 ios

当我NSNumber使用'floatValue' 转换为浮点值时,精度会有所不同.例如,我的NSNumber'myNumber'值为2.3,如果我使用'floatValue'将myNumber转换为float,则其值为2.29999.但我需要2.30000.2.3之后零的数量没有问题,我需要'2.3'而不是'2.9'.

我怎么能这样做?

Hit*_*iya 7

我有类似的情况,我正在读取值并再次将其分配给浮点变量.

我的问题陈述:

 NSString *value = @"553637.90";
 NSNumber *num = @([value floatValue]); // 1. This is the problem. num is set to 553637.875000     
 NSNumberFormatter *decimalStyleFormatter = [[NSNumberFormatter alloc] init];
 [decimalStyleFormatter setMaximumFractionDigits:2];
 NSString *resultString = [decimalStyleFormatter stringFromNumber:num]; // 2. string is assigned with rounded value like 553637.88
 float originalValue = [resultString floatValue]; // 3. Hence, originalValue turns out to be 553637.88 which wrong.
Run Code Online (Sandbox Code Playgroud)

改变线后为我工作:

    NSNumber *num = @([value doubleValue]); // 4. doubleValue preserves value 553637.9
    double originalvalue = [resultString doubleValue]; // 5. While reading back, assign to variable of type double, in this case 'originalValue'
Run Code Online (Sandbox Code Playgroud)

我希望这会有所帮助.:)