当我使用“floatValue”将 NSNumber
转换为浮点值时,精度有所不同。例如,我有一个值为 2.3 的 NSNumber
'myNumber',如果我使用 'floatValue' 将 myNumber 转换为 float ,它的值变为 2.29999。但我正好需要 2.30000。 2.3 之后的零个数没有问题,我需要“2.3”而不是“2.9”。
我该怎么做?
最佳答案
我遇到过类似的情况,我正在读取值并将其重新分配回 float 变量。
我的问题陈述:
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.
以下在更改行后对我有用:
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'
希望对您有所帮助。 :)
关于ios - NSNumber 到浮点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15087645/